Should I use `void 0` or `undefined` in JavaScript

Javascript

Javascript Problem Overview


Should I use void 0 or undefined in JavaScript to unassign a value, for example:

event.returnValue = void 0;

or

event.returnValue = undefined;

Javascript Solutions


Solution 1 - Javascript

If you are using a modern browser, (which supports JavaScript 1.8.5) using undefined and void 0 would most likely yield the same result (since undefined is made not writable), except that the void can accept an expression as parameter and evaluate it.

In older browsers, (which do not support JavaScript 1.8.5) it is better to use void 0. Look at this example:

console.log(undefined);
var undefined = 1;
console.log(undefined);

It will print

1

undefined is actually a global property - it's not a keyword. So, undefined can be changed, where as void is an operator, which cannot be overridden in JavaScript and always returns the value undefined. Just check this answer which I gave earlier today for a similar question, Why does void in Javascript require an argument?.

Conclusion:

So, if you are concerned about compatibility, it is better to go with void 0.

Solution 2 - Javascript

"void 0" is safer. "undefined" is a value, like any other. It's possible to overwrite that value with another:

undefined = 3;

That would change the meaning of your event.returnValue had you used undefined. "void" is a keyword, though, and its meaning can't be changed. "void 0" will always give the value undefined.

Solution 3 - Javascript

>The void operator is often used merely to obtain the undefined primitive value, usually using “void(0)” (which is equivalent to “void 0”). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

https://stackoverflow.com/a/1291950/2876804

Just use undefined, since they will both evaluate to it.

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
QuestionavoView Question on Stackoverflow
Solution 1 - JavascriptthefourtheyeView Answer on Stackoverflow
Solution 2 - JavascriptZachView Answer on Stackoverflow
Solution 3 - Javascriptshade4159View Answer on Stackoverflow