JavaScript Reference ยท Operators
The void operator
Reference for the JavaScript void operator: evaluating an expression and returning undefined, void 0, javascript: URLs and discarding return values.
The void operator evaluates an expression and then throws the result away, always returning undefined. It is rare in modern code, but you still see it in minified output (void 0 is a short way to write undefined) and in places where you want to be sure a value is ignored.
void expression
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
void expr
| Operand | Description |
|---|---|
expr |
Any expression. It is evaluated for its side effects. |
Return value: always undefined.
Exceptions: none of its own. If evaluating expr throws, the error propagates.
Usage notes
void 0versusundefined: in old scriptsundefinedcould be reassigned inside a function, sovoid 0was the safe way to get the real value. Todayundefinedis read-only at the global level and a shadowed local namedundefinedis unusual, so writeundefinedunless you are minifying.- Precedence is high:
void 1 + 2is(void 1) + 2, which isNaN. Use parentheses:void (1 + 2). - Ignoring promises:
void fetchData()tells readers (and some linters, for example a "no floating promises" rule) that you deliberately aren't awaiting the result. It does not handle rejections: add a.catch()if the promise can fail. - Arrow functions:
() => void doSomething()makes sure a callback returns nothing, which matters when a caller treats a returned value specially (for example, a returned function in some frameworks). javascript:URLs:href="javascript:void(0)"stops the browser from navigating to the result of the expression. It is an old pattern; use a<button>instead, and avoidjavascript:URLs because they are blocked by many content security policies.- Statements:
voidneeds an expression. It can't wrap anifor a loop. - Not the same as
typeof:typeof xreturns a string,void xalwaysundefined.
Browser support
Supported in every browser and runtime.