The MDN article on the void
operator mentions a clever way to declare an immediately invoked function expression (IIFE).
void function() {
console.log('hello');
}();
// is the same as...
(function() {
console.log('hello');
})();
I think using void
for this looks pretty nice. Traditional IIFEs have a lot of parentheses that I find visually confusing.
Then I tried rewriting this code with an arrow function.
void () => {
console.log('hello');
}();
This doesn't parse. Chrome says, "Uncaught SyntaxError: Unexpected token )" on line 1, where the arrow function is defined. Firefox says, "SyntaxError: invalid arrow-function arguments (parentheses around the arrow-function may help)".
It doesn't even parse when the function isn't invoked.
void () => {
console.log('hello');
};
I've tried reading about this (including other SO questions like this one and this one).
I guess it has something to do with arrow functions being AssignmentExpressions…? But I get lost trying to follow the ECMA-262 specification.