I have an IIFE that works, but when I rewrite it using an arrow function, it does not work!
1.- This one works fine:
let j = 3;
(function (n) {
while (n--)
console.log("n only", n);
}(j));
2.- This one doesn't work!:
((n) => {
while (n--)
console.log("n only", n);
}(j));
3.- I have already tested the next version which works too:
((n) => {
while (n--)
console.log("n only", n);
})(j);
But I really want to understant why the version on (2) does not work.
This is how the language defined it. As mdn states:
Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.
It continues to give another example, but the principle is the same:
let callback; callback = callback || function() {}; // ok callback = callback || () => {}; // SyntaxError: invalid arrow-function arguments callback = callback || (() => {}); // ok
Although Crockford expressed a preference for putting the closing parenthesis of an IIFE at the very end (after the arguments), I personally find it more intuitive to put it at the same place as where it is required for arrow functions (after the closing brace, before the arguments).
The reason is that the purpose of the parentheses is to turn a function into a function expression and so the arguments really aren't significant in that conversion. So this seems just more to the point:
(function (n) => {
while (n--)
console.log("n only", n);
})(j);