ES6 immediately invoked arrow function

XCS picture XCS · Jan 4, 2016 · Viewed 68.6k times · Source

Why does this work in a Node.js console (tested in 4.1.1 and 5.3.0) but doesn't work in the browser (tested in Chrome)? This code block should create and invoke an anonymous function that logs Ok.

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

Also, while the above works in Node, this does not work:

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

Nor this:

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

What's odd is that when the parameter is added it actually throws a SyntaxError at the immediately-invoking part.

Answer

void picture void · Jan 4, 2016

You need to make it a function expression instead of function definition which doesnt 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 and firefox and most of the browser interprets 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');
})()