Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript `undefined` vs `void 0`

What exactly is the difference between undefined and void 0 ?

Which is preferred and why?

like image 510
Pacerier Avatar asked Apr 19 '11 13:04

Pacerier


People also ask

Is void 0 same as undefined?

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 .

What does void 0 do in JavaScript?

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.

Is JavaScript void 0 Safe?

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).

Is undefined 0 in JS?

If the value is equal to undefined , the operator returns 0 , otherwise the value is returned. Copied!


1 Answers

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 
like image 117
duri Avatar answered Sep 20 '22 20:09

duri