8

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.

Dan Fabulich
  • 31,628
  • 35
  • 121
  • 153

1 Answers1

6

I'd say Paul S. explained why: arrow functions have a very low "operator precedence", they cannot be used as operands of other operators, except for assignments, yield and the comma operator. This was made so that you can still use all those other operators in concise bodies, and that they are still easy to parse.

To pass them to the void operator, you'd have to wrap them in grouping parenthesis (which of course defeats the point of using void for the IIFE).

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • "which of course defeats the point of using void for the IIFE". Considering the poor design of JavaScript ASI, `void` is helpful when you prefer to terminate statements with just LF without semicolons, and do not like semicolon at the beginning of line. – weakish Dec 08 '19 at 07:05