JavaScript `undefined` vs `void 0`

JavascriptUndefinedVoid

Javascript Problem Overview


What exactly is the difference between undefined and void 0 ?

Which is preferred and why?

Javascript Solutions


Solution 1 - Javascript

The difference is that some browsers allow you to overwrite the value of undefined. However, void anything always returns real undefined.

undefined = 1;
console.log(!!undefined); //true
console.log(!!void 0); //false

Solution 2 - Javascript

undefined has normal variable semantics that not even strict mode can fix and requires run-time look-up. It can be shadowed like any other variable, and the default global variable undefined is not read-only in ES3.

void 0 is effectively a compile time bulletproof constant for undefined with no look-up requirements. It is like writing null or true, instead of looking up a variable value. It works out of the box without any safety arguments and is shorter to write. It is better in every way.

Solution 3 - Javascript

Use undefined. Its more commonly known than void(0).

Solution 4 - Javascript

Parentheses here are optional, void 0, void(0) and void (0) are equivalent. The void is a unary operator with a right-to-left associativity, hence the value is placed at the right of it:

void <VALUE>.

For second question, you need to use undefined directly while avoiding unneeded operand evaluation to retrieve the same undefined value.

More info in the reference: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/void

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPacerierView Question on Stackoverflow
Solution 1 - JavascriptduriView Answer on Stackoverflow
Solution 2 - JavascriptEsailijaView Answer on Stackoverflow
Solution 3 - JavascriptDaniel A. WhiteView Answer on Stackoverflow
Solution 4 - Javascriptuser422039View Answer on Stackoverflow