ES6 immediately invoked arrow function

Javascriptnode.jsArrow Functions

Javascript Problem Overview


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.js, this does not work:

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

Nor this:

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

It is odd that when the parameter is added, it actually throws a SyntaxError at the immediately-invoking part.

Javascript Solutions


Solution 1 - Javascript

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');
})()

Solution 2 - Javascript

None of these should work without parentheses.

Why?

Because according in the spec:

  1. ArrowFunction is listed under AssignmentExpression
  2. The LHS of a CallExpression must be a MemberExpression, SuperCall or CallExpression

So an ArrowFunction cannot be on the LHS of a CallExpression.


What this effectively means in how => should be interpreted, is that it works on the same sort of level as assignment operators =, += etc.

Meaning

  • x => {foo}() doesn't become (x => {foo})()
  • The interpreter tries to interpret it as x => ({foo}())
  • Thus it's still a SyntaxError
  • So the interpreter decides that the ( must have been wrong and throws a SyntaxError

There was a bug on Babel about it here, too.

Solution 3 - Javascript

The reason you're seeing problems like this is that the console itself tries to emulate the global scope of the context you're currently targeting. It also tries to capture return values from statements and expressions you write in the console, so that the show up as results. Take, for instance:

> 3 + 2
< 5

Here, it executes as though it were an expression, but you've written it as though it were a statement. In normal scripts, the value would be discarded, but here, the code must be internally mangled (like wrapping the entire statement with a function context and a return statement), which causes all sorts of weird effects, including the problems you're experiencing.

This is also one of the reasons why some bare ES6 code in scripts works fine but doesn't in Chrome Dev Tools console.

Try executing this in Node and Chrome console:

{ let a = 3 }

In Node or a <script> tag it works just fine, but in the console, it gives Uncaught SyntaxError: Unexpected identifier. It also gives you a link to the source in the form of VMxxx:1 which you can click to inspect the evaluated source, which shows up as:

({ let a = 3 })

So why did it do this?

The answer is that it needs to convert your code into an expression so that the result can be returned to the caller and displayed in the console. You can do this by wrapping the statement in parentheses, which makes it an expression, but it also makes the block above syntactically incorrect (an expression cannot have a block declaration).

The console does try to fix these edge cases by being smart about the code, but that's beyond the scope of this answer, I think. You can file a bug to see if that's something they'd consider fixing.

Here's a good example of something very similar:

https://stackoverflow.com/a/28431346/46588

The safest way to make your code work is to make sure it can be run as an expression and inspect the SyntaxError source link to see what the actual execution code is and reverse engineer a solution from that. Usually it means a pair of strategically placed parentheses.

In short: the console tries to emulate the global execution context as accurately as possible, but due to the limitations of interaction with the v8 engine and JavaScript semantics this is sometimes hard or impossible to solve.

Solution 4 - Javascript

I asked a question like this:

> @getify I’ve this question: to produce an #IIFE pattern we use parans around a function declaration to transform it into a function expression and then invoke it. Now in arrow function IIFEs, why do we need parans?! Isn’t the arrow function already an expression by default?!

and this is the Kyle Simpson's answer:

> an arrow function is an expr, but we need surrounding parens b/c of "operator precedence" (sorta), so that the final parens to invoke the arrow-IIFE apply to the entire function and not to just the last token of its body.

x => console.log(x)(4)    // trouble

vs

(x => console.log(x))(4)    // working

— getify (@getify) https://twitter.com/getify/status/1271459902570082307?ref_src=twsrc%5Etfw">June 12, 2020

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionXCSView Question on Stackoverflow
Solution 1 - JavascriptvoidView Answer on Stackoverflow
Solution 2 - JavascriptPaul S.View Answer on Stackoverflow
Solution 3 - JavascriptKlemen SlavičView Answer on Stackoverflow
Solution 4 - JavascriptErshad QaderiView Answer on Stackoverflow