Sometimes I see such links
& lt; a href = "javascript: void (0)" & gt; Login & lt; / a & gt;
and void 0
are also used in the Backbone.js library, for example:
if (obj == null) return void 0;
What does void 0
mean and what is it for?
Answer 1, authority 100%
Operator void
[MDN] sup>[specification] evaluates the passed expression and always returns undefined
.
Examples:
void 0 // returns undefined
void (0) // this also returns undefined
void "hello" // also returns undefined
void new Date () // always returns undefined
Why is this operator needed at all?
If void 0
always returns undefined
, you can just use undefined
, no?
You can. In fact, void
is not a very useful operator and I rarely use it. But it comes in handy in some situations:
-
In older browsers (I’m not sure which ones. In my opinion, in IE 6 and below and in Netscape) it was possible to change the value of
undefined
:undefined = 5; // in older browsers will change the value to undefined, // does nothing in new ones 5 === undefined; // true in older browsers, false in newer
It is not always known that
undefined
meansundefined
. Therefore, some libraries usevoid 0
. -
Even in newer browsers
undefined
is a valid variable name inside a function:function f () { var undefined = 5; return undefined; } f (); // returns 5
But if you write code like this, it’s your fault.
- If you want to save your energy:
void 0
is three characters shorter thanundefined
. Although0 [0]
is even shorter.
A link starting with javascript:
usually sends the user to a page with the text that the code returns. For example:
Press & lt; a href = "javascript: 'Hello!'" & gt; HERE & lt; / a & gt ;!