Skip to main content

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

javascript
void expression

or

javascript
void(expression)

Main idea

The void operator evaluates the expression, but always returns undefined.


Example

javascript
void 123; // undefined void 'hello'; // undefined void (5 + 5); // undefined

It doesn't matter what the expression on the right evaluates to, the result of void is always undefined.


Example with a function

javascript
function sayHi() { console.log('Hello!'); return 'Hi'; } console.log(sayHi()); // "Hi" console.log(void sayHi()); // runs, but returns undefined

Here, sayHi() is called, but the result ('Hi') is ignored, and undefined is returned.


Where it's used in practice

Sometimes you need a link click to do nothing:

javascript
<a href="javascript:void(0)">Click me</a>

Here:

  • void(0) is executed → undefined
  • the browser doesn't navigate anywhere, because href doesn'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:

javascript
void function() { console.log('It worked!'); }();

Without void, the parser could confuse the expression with a function declaration. This need is rare nowadays, but historically void was used as a "safety net".


In arrow functions, to "return nothing"

javascript
const log = msg => void console.log(msg); log('Hello'); // logs to the console, but returns undefined

Here, void is used to perform an action without returning a value.


In bookmarklets (mini-scripts in bookmarks)

An example of a "bookmarklet":

javascript
javascript:void(alert('Hello'))

Without void, the browser would try to navigate to a "page" with the expression's result (e.g., undefined), and void prevents that.


Example: comparison with a regular call

javascript
function calc() { return 42; } console.log(calc()); // 42 console.log(void calc()); // undefined

The function runs, but void forces the expression to return undefined.


Summary

What it doesEvaluates an expression and returns undefined
Returnsundefined
Used forIgnoring the expression's result
Common scenariosjavascript:void(0) links, IIFEs, arrow functions without a return

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.