TIL: JavaScript's void Operator

matheusrich

Matheus Richard

Posted on January 21, 2022

TIL: JavaScript's void Operator

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

console.log(void "hello world") // prints `undefined`
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
matheusrich
Matheus Richard

Posted on January 21, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related