Sometimes undefined is defined
There was always some confusion around
void 0 in some cases.
This is the actual execution semantics of undefined. On the syntax level
undefined is just an arbitrary identifier — in contrast to
undefined on the global object, which is what most people expect.
Thanks to funny language constructs like
with this could even be hidden somewhat, for example using
Or using a
The same applies to
NaN by the way, which is also just a non-writable, non-configurable property of the global object. This is pretty confusing, and one of the best reasons for not using
with in your code.
You can avoid these problems by using the void operator instead of
undefined when you want the actual value undefined — and trust me, you always want that if you write
void operator always yields the undefined value. Since the expression passed to it is evaluated, but the result is not used, any side effect expression will do the trick for us. I’d suggest to stick to
void 0, since that’s short and easy to spot.
Now the program does what we want it to do.
Obviously there’s also the performance aspect here. V8 is actually pretty smart when it comes to avoiding the property lookup for
undefined in many cases. In fact, V8 will always constant-fold
undefined to the actual undefined value as long as you don’t have any
with in your scope chain.
getUndefined function above — at least not on the bytecode level:
In summary: Be aware that writing
void 0 instead.