The void operator
The void operator in JavaScript is a fairly rare but important tool.
It is used to evaluate an expression without returning a value,
meaning it always returns undefined, regardless of what the expression does.
Syntax
void expressionor
void(expression)Main idea
The
voidoperator evaluates the expression, but always returnsundefined.
Example
void 123; // undefined
void 'hello'; // undefined
void (5 + 5); // undefinedIt doesn't matter what the expression on the right evaluates to, the result of
voidis alwaysundefined.
Example with a function
function sayHi() {
console.log('Hello!');
return 'Hi';
}
console.log(sayHi()); // "Hi"
console.log(void sayHi()); // runs, but returns undefinedHere, sayHi() is called,
but the result ('Hi') is ignored, and undefined is returned.
Where it's used in practice
To prevent navigation via an <a> link
Sometimes you need a link click to do nothing:
<a href="javascript:void(0)">Click me</a>Here:
void(0)is executed →undefined- the browser doesn't navigate anywhere, because
hrefdoesn't provide a URL.
This is a legacy practice;
in modern code it's better to use href="#" with event.preventDefault().
For IIFEs (immediately invoked function expressions)
void used to be used to guarantee correct execution of an IIFE:
void function() {
console.log('It worked!');
}();Without
void, the parser could confuse the expression with a function declaration. This need is rare nowadays, but historicallyvoidwas used as a "safety net".
In arrow functions, to "return nothing"
const log = msg => void console.log(msg);
log('Hello'); // logs to the console, but returns undefinedHere,
voidis used to perform an action without returning a value.
In bookmarklets (mini-scripts in bookmarks)
An example of a "bookmarklet":
javascript:void(alert('Hello'))Without
void, the browser would try to navigate to a "page" with the expression's result (e.g.,undefined), andvoidprevents that.
Example: comparison with a regular call
function calc() {
return 42;
}
console.log(calc()); // 42
console.log(void calc()); // undefinedThe function runs, but
voidforces the expression to returnundefined.
Summary
| What it does | Evaluates an expression and returns undefined |
|---|---|
| Returns | undefined |
| Used for | Ignoring the expression's result |
| Common scenarios | javascript:void(0) links, IIFEs, arrow functions without a return |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.