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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What does
void 0mean?void[MDN] is a prefix keyword that takes one argument and always returnsundefined.Examples
What’s the point of that?
It seems pretty useless, doesn’t it? If it always returns
undefined, what’s wrong with just usingundefineditself?In a perfect world we would be able to safely just use
undefined: it’s much simpler and easier to understand thanvoid 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
undefinedwas thatundefinedis not a reserved word (it is actually a property of the global object [wtfjs]). That is,undefinedis a permissible variable name, so you could assign a new value to it at your own caprice.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
undefinedproperty 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.void, on the other hand, cannot be overidden.void 0will always returnundefined.undefined, on the other hand, can be whatever Mr. Javascript decides he wants it to be.Why
void 0, specifically?Why should we use
void 0? What’s so special about0? Couldn’t we just as easily use1, or42, or1000000or"Hello, world!"?And the answer is, yes, we could, and it would work just as well. The only benefit of passing in
0instead of some other argument is that0is short and idiomatic.Why is this still relevant?
Although
undefinedcan generally be trusted in modern JavaScript environments, there is one trivial advantage ofvoid 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 replaceundefinedwithvoid 0to reduce the number of bytes sent to the browser.