Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 immediately invoked arrow function

People also ask

Can arrow functions be invoked?

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.

Why use immediately invoked function JavaScript?

An Immediately-invoked Function Expression is a way to execute functions immediately, as soon as they are created. IIFEs are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations.

Do immediately invoked functions wait for a function call to be executed?

An Immediate-Invoked Function Expression (IIFE) is a function that is executed instantly after it's defined. This pattern has been used to alias global variables, make variables and functions private and to ensure asynchronous code in loops are executed correctly.

What does => mean in ES6?

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.


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

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.


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.


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) June 12, 2020