Let expr be the result of evaluating UnaryExpression.
Perform ? GetValue(expr).
Return undefined.
NOTE: GetValue must be called even though its value is not used because it may have observable side‐effects.
Examples
> void 0 // same as void(0)
undefined
> void 4+7 // same as (void 4)+7
NaN
> void(4+7)
undefined
> var x = 3;
3
> void(x = 5);
undefined
> x
5
Use case
void 0 as undefined
void 0 and void(0) are the same as undefined, with one exception: undefined can be shadowed or redefined. So if you are paranoid about shadowing or globally changing undefined, use void 0.
Immediately Invoked Function Expressions(IIFE)
When using an IIFE, void can be used to force the function keyword to be treated as an expression instead of a declaration.
> void function () { console.log(1) }()
1
undefined
JavaScript URIs
A javascript: URI evaluates the code in the URI and then replaces the contents of the page with the returned value unless the returned value is undefined.
So we can often find <a href="javascript:void(0);"> in HTML. The reason you’d want to do this with the href of a link is that the void operator can be used to return undefined.
the void Operator
Syntax: void UnaryExpression
expr
be the result of evaluating UnaryExpression.GetValue(expr)
.undefined
.NOTE: GetValue must be called even though its value is not used because it may have observable side‐effects.
Examples
Use case
void 0
asundefined
void 0
andvoid(0)
are the same asundefined
, with one exception:undefined
can be shadowed or redefined. So if you are paranoid about shadowing or globally changingundefined
, usevoid 0
.When using an IIFE,
void
can be used to force the function keyword to be treated as an expression instead of a declaration.A
javascript: URI
evaluates the code in theURI
and then replaces the contents of the page with the returned value unless the returned value isundefined
. So we can often find<a href="javascript:void(0);">
in HTML. The reason you’d want to do this with thehref
of a link is that the void operator can be used to returnundefined
.Reference
http://2ality.com/2011/05/void-operator.html http://adripofjavascript.com/blog/drips/javascripts-void-operator.html https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void