Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I make a void arrow function?

Tags:

javascript

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.

like image 204
Dan Fabulich Avatar asked Jan 20 '18 19:01

Dan Fabulich


People also ask

What does () => void mean TypeScript?

The syntax (a: string) => void means “a function with one parameter, named a , of type string, that doesn't have a return value”. Just like with function declarations, if a parameter type isn't specified, it's implicitly any .

Is void 0 undefined?

The void operator is often used merely to obtain the undefined primitive value, usually using void(0) (which is equivalent to void 0 ). In these cases, the global variable undefined can be used.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

How do you call a void function in JavaScript?

To achieve it, we combine the pseudo URL (javascript:) with void(0) as a value of an href, it tells the browser to return/do nothing when that link is clicked.


1 Answers

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).

like image 56
Bergi Avatar answered Sep 21 '22 18:09

Bergi