Should I use void 0
or undefined
in JavaScript to unassign a value, for example:
event.returnValue = void 0;
or
event.returnValue = undefined;
Using javascript: , you can run code that does not change the current page. This, used with void(0) means, do nothing - don't reload, don't navigate, do not run any code.
In JavaScript code, especially in older legacy code, you sometimes find the expression void 0 . The void operator evaluates an expression and returns the primitive value undefined. void 0 evaluates 0 , which does nothing, and then returns undefined . It is effectively an alias for undefined .
JavaScript void 0 means returning undefined (void) as a primitive value. You might come across the term “JavaScript:void(0)” while going through HTML documents. It is used to prevent any side effects caused while inserting an expression in a web page.
void <expression> It is an operator. Unlike both undefined and null , it does not represent a primitive value. The connection between void and the other two is that it always returns the value of undefined . Its purpose is to evaluate an expression (usually for its side effects) and then return undefined .
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
.
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With