The void operator in JavaScript
Join the DZone community and get the full member experience.
Join For FreeSyntax:
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; }
In contrast, void cannot be redefined:
a()
’hello’function b() { var void = function() {}; return void(0); }
This results in a syntax error complaining about a “missing variable name” (after var).
Topics:
Opinions expressed by DZone contributors are their own.
Comments