ES6 immediately invoked arrow function

You need to make it a function expression instead of function definition which doesn’t need a name and makes it a valid JavaScript.

(() => {
  console.log('Ok');
})();

Is the equivalent of IIFE

(function() {
   console.log('Ok');
})();

And the possible reason why this works in Node.js but not in Chrome, is because its parser interprets it as a self-executing function, as this

function() { console.log('hello'); }();

works fine in Node.js. This is a function expression, and Chrome, Firefox, and most browsers interpret it this way. You need to invoke it manually.

The most widely accepted way to tell the parser to expect a function expression is just to wrap it in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.

Regarding the parametrized version, this will work.

((n) => {
  console.log('Ok');
})()

Leave a Comment