Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

The void operator in JavaScript

DZone's Guide to

The void operator in JavaScript

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Syntax:

    void expr

evaluates expr and returns undefined. Its (rare) use is for contexts where an expression is demanded, but the result has to be undefined. Example: javascript URLs in browsers display the result of an expression, unless it is undefined. Compare:

  • javascript:3+4 displays 7 as the current document.
  • javascript:void(3+4) does not change the current document. void “hides” the result of the expression 3+4.

Similarly:

  • javascript:window.open("http://www.whitehouse.gov/") replaces the content of the current page.
  • javascript:void window.open("http://www.whitehouse.gov/") does not change the content of the current page.

Comments:

  • The operator binds very closely, thus you should put parentheses around its argument if it contains more than a single token. For example, void 3+4 binds as (void 3)+4.
  • void 0 and void(0) are the same as undefined, with one exception: undefined can be shadowed.
        function a() { var undefined = "hello"; return undefined; }
    a()
    ’hello’
    In contrast, void cannot be redefined:
       function b() { var void = function() {}; return void(0); }
    This results in a syntax error complaining about a “missing variable name” (after var).

From http://www.2ality.com/2011/05/void-operator.html

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}