What does `void 0` mean? [duplicate]
Reading through the Backbone.js source code, I saw this:
validObj[attr] = void 0;
What is void 0? What is the purpose of using it here?
void 0 mean?
void[MDN] is a prefix keyword that takes one argument and always returns
void 0 void (0) void "hello" void (new Date()) //all will return undefined
What’s the point of that?
It seems pretty useless, doesn’t it? If it always returns
undefined, what’s wrong with just using
In a perfect world we would be able to safely just use
undefined: it’s much simpler and easier to understand than
The problem with using
undefined was that
undefined is not a reserved word (it is actually a property of the global object [wtfjs]). That is,
undefined is a permissible variable name, so you could assign a new value to it at your own caprice.
alert(undefined); //alerts "undefined" var undefined = "new value"; alert(undefined) // alerts "new value"
Note: This is no longer a problem in any environment that supports ECMAScript 5 or newer (i.e. in practice everywhere but IE 8), which defines the
undefined property of the global object as read-only (so it is only possible to shadow the variable in your own local scope). However, this information is still useful for backwards-compatibility purposes.
alert(window.hasOwnProperty('undefined')); // alerts "true" alert(window.undefined); // alerts "undefined" alert(undefined === window.undefined); // alerts "true" var undefined = "new value"; alert(undefined); // alerts "new value" alert(undefined === window.undefined); // alerts "false"
void, on the other hand, cannot be overidden.
void 0 will always return
void 0, specifically?
Why should we use
void 0? What’s so special about
0? Couldn’t we just as easily use
And the answer is, yes, we could, and it would work just as well. The only benefit of passing in
0 instead of some other argument is that
0 is short and idiomatic.
Why is this still relevant?
void 0: it’s shorter. The difference is not enough to worry about when writing code but it can add up enough over large code bases that most code minifiers replace
void 0 to reduce the number of bytes sent to the browser.
void 0 returns undefined and can not be overwritten while
undefined can be overwritten.
var undefined = "HAHA";