Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use void(0)? [duplicate]

Let's assume for a moment that you must create a JavaScript link that doesn't have a meaningful href. (I know that this practice is questionable.) In this case, why do so many people use...

<a href="javascript:void(0);"> My link </a> 

Knowing that void(0) evaluates to undefined, can I simply use the following logic?

<a href="javascript:undefined;"> My link </a>
like image 528
hawkharris Avatar asked Oct 03 '22 02:10

hawkharris


2 Answers

Why people use void(x) instead of undefined?

Well both would work but undefined is a reserved variable and its value can be changed:

undefined = true;

This will give true instead of undefined.

Where as void() is a keyword which always returns undefined. Whatever you place inside the keyword:

void('return false plox'); //will return false

More info on this topic here: What does `void 0` mean?

jsFiddle


Note that <a href="#"> is not the same as it still acts as a link and will redirect you, where as the previous methods will cancel the event(similar to event.preventDefault).

Update

Since ECMAScript 5, the global undefined variable is no longer directly editable (See for example Mozilla docs). It now simply shadows the global variable as some have noted.

like image 138
nkmol Avatar answered Oct 13 '22 10:10

nkmol


There are three differences,

  1. void evaluates the given expression and then returns the undefined
  2. window.undefined is writable whereas void operator will always return undefined
  3. void has fewer characters and results in smaller code, if you are using lot of them

Also, if you are using void to return undefined then you can simply use void 0, which is equivalent to void(0).

like image 25
Sajad Deyargaroo Avatar answered Oct 13 '22 10:10

Sajad Deyargaroo