Sometimes undefined is defined

There was always some confusion around undefined in JavaScript. I’ll try to shed some light on it, and highlight why it might be better — i.e. safer and/or faster — to write void 0 in some cases.

EcmaScript contains a special type Undefined, which has exactly one value, called undefined.

This is the actual execution semantics of undefined. On the syntax level undefined is just an arbitrary identifier — in contrast to null, true and false, which are keywords in JavaScript. That means, when you write undefined in a JavaScript program, you actually refer to a previously bound name. By default this will result in looking up the name undefined on the global object, which is what most people expect.

However, since it’s just a regular variable name, it can be used as such in arbitrary ways. For example this is perfectly reasonable code — from the perspective of the JavaScript language:

Thanks to funny language constructs like eval or with this could even be hidden somewhat, for example using eval:

Or using a with scope:

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 eval or 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 undefined.

The 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 eval or with in your scope chain.

However, other JavaScript engines might not have this optimization. For example JavaScriptCore — the engine inside Safari — doesn’t apply this optimization for the getUndefined function above — at least not on the bytecode level:

In summary: Be aware that writing undefined in your JavaScript might not always produce the value undefined, depending on the surrounding code. It might be safer and faster to use void 0 instead.

Like what you read? Give Benedikt Meurer a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.