The expression "Invoked Expression" immediately: where to put the brackets?

I saw IIFE write:

(function() { console.log("do cool stuff"); })(); 

and:

 (function() { console.log("do more cool stuff"); }()); 

They seem to work the same in any context that I used, although in cases where I was told that one of the methods is right and the other is wrong, vice versa. Does anyone have a solid reason or logic as it is written in one order over another? Are there some cases where potential expansion can occur after the function body closes, but before the calling bracket enters the game or after it, but before this final closing bracket? I mainly used them in closing the Angular module and cannot find anything for any real reason to go anyway, wondering if anyone else has experience.

+7
javascript iife
source share
1 answer

Short answer: It doesn’t matter if you put them there.

Long answer: It doesn’t matter, because only what they are is important for JavaScript. The reason for this is because the language specification determines that an operator should start with the function keyword if you declare a named function. Therefore, it is contrary to the specification to define IIFE like this:

 function () {}(); 

The workaround for this is to wrap the whole thing in parentheses so that the statement no longer starts with the keyword function . You achieve this using

 (function () {})(); 

as well as using:

 (function () {}()); 

Which one you choose is completely arbitrary and therefore up to you.

I (personally) put parentheses around a function, not around a call, for example:

 (function () {})(); 

Cause. I want to use the smallest part of the code, which will be wrapped up in what is required only for technical reasons, and this is a function definition, not a call. In addition, the specification says that you cannot define a function in this way; it is not a function call. Therefore, I find this more clear if you complete the definition, not the call.

+8
source share

All Articles