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 undefined
.
Examples
void 0
void (0)
void "hello"
void (new Date())
//all will return undefined
It seems pretty useless, doesn't it? If it always returns undefined
, what's wrong with just using undefined
itself?
In a perfect world we would be able to safely just use undefined
: it's much simpler and easier to understand than void 0
. But in case you've never noticed before, this isn't a perfect world, especially when it comes to Javascript.
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 undefined
. undefined
, on the other hand, can be whatever Mr. Javascript decides he wants it to be.
void 0
, specifically?Why should we use void 0
? What's so special about 0
? Couldn't we just as easily use 1
, or 42
, or 1000000
or "Hello, world!"
?
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.
Although undefined
can generally be trusted in modern JavaScript environments, there is one trivial advantage of 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 undefined
with void 0
to reduce the number of bytes sent to the browser.