Akiq2016 / blog

notes
4 stars 0 forks source link

what-is-void-in-javascript #10

Open Akiq2016 opened 6 years ago

Akiq2016 commented 6 years ago

the void Operator

Syntax: void UnaryExpression

  1. Let expr be the result of evaluating UnaryExpression.
  2. Perform ? GetValue(expr).
  3. 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

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

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

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

marionetteliu commented 5 years ago

强鸭