TIL: JavaScript's void Operator
Matheus Richard
Posted on January 21, 2022
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
💖 💪 🙅 🚩
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
todayilearned The difference between Promise.all() vs Promise.allSettled() vs Promise.any() vs Promise.race() in 30 seconds
April 26, 2024
todayilearned Have you noticed that you can short-circuiting the spread operator?
September 23, 2022