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.
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 .
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With