Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use `void 0` or `undefined` in JavaScript [duplicate]

Tags:

javascript

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

event.returnValue = void 0; 

or

event.returnValue = undefined; 
like image 460
avo Avatar asked Oct 14 '13 20:10

avo


People also ask

Is JavaScript void 0 Safe?

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.

Is void 0 same as undefined?

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 .

Why do we use void 0 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.

What is difference between null or void in JavaScript?

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 .


2 Answers

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.

like image 55
thefourtheye Avatar answered Sep 29 '22 05:09

thefourtheye


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

like image 45
Zach Avatar answered Sep 29 '22 05:09

Zach