~ RICH CODES

TIL: JavaScript's void Operator

January 20, 2022 | 1 minute read | ✍🏼 Edit this page

Today I discovered the void operator in JavaScript. It evaluates an expression but always returns undefined.

console.log(void "hello world") // prints `undefined`

It can be used on a IIFE , which usually uses parenthesis to make the function definition be interpreted as an expression and not a declaration:

void function() {
  console.log("hello world")
}();
// prints "hello world"


(function() {
  console.log("hello world")
})();
// prints "hello world"

function() {
  console.log("hello world")
}();
// SyntaxError

This operator is also useful to ensure that an arrow function always return undefined:

// changes to the return value of `doSomething` won't affect this code
button.onclick = () => void doSomething();

Caveat

It’s important to note that this operator has a high precedence with right-to-left associativity, so you may want to use parenthesis to correctly construct some expressions:

void "hello" + " world" // parsed as: (void "hello") + " world"
// => 'undefined world'

void ("hello" + " world") // parsed as: void ("hello" + " world")
// => undefined

Categories

TIL javascript