Today I discovered the voidoperator 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
Top comments (1)
Fun fact. early on you used to be able to redefine the undefined keyword in ES5, e.g.
so Babel, would convert any
undefineds it found tovoid 0More on that here
I noticed that using
envpreset Babel turns all instances ofundefinedintovoid 0.Arguments in favour of
void 0are mainly void (pun intended):undefinedfrom reassigning. This is not relevant now since ES5 spec was released a decade ago which prohibits that. Since then, you can't reassignundefinedprimitive.undefined. Three characters less. But minifying is not the purpose of Babel, is it?Arguments against
void 0:voidis operator,undefinedis primitive type. By definition, primitive type is more efficient to process than operator whose result is the same primitive type. The difference might be negligible but I haven't seenvoid 0vsundefinedperf tests proving that.void 0as a code bug, which means if you review Babel CommonJS build file (coming from Rollup typically), you'll see linting errors everywhere where you previously usedundefinedvoid 0is an unnecessary burden to learn and obfuscated Babel builds make it more difficult to understand what Babel does.I know, this is not a bug per se or a feature per se, but nonetheless it's an important, fundamental issue that needs to be looked at. I see no reason why we should transpile down to ES3 JS spec (because, technically, that's what we're doing at the moment).
Thank you.
and here's the a plugin in regards to this as well.
babeljs.io/docs/en/babel-plugin-tr...