What exactly is the difference between undefined
and void 0
?
Which is preferred and why?
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.
Generally, you want to avoid href="javascript:void(0)" , as it will cause the browser to parse the value of the link URL, which is both costly and unnecessary. It also introduces a potential XSS security vulnerability, as javascript: URLs violate Content Security Policy (CSP).
If the value is equal to undefined , the operator returns 0 , otherwise the value is returned. Copied!
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
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