This question has already been answered:

I understand why we need a module and just why encapsulation is needed. However, I can’t understand what its syntax is (function(){ код })() .

Where do brackets come from and what do brackets do around the function

Why and how do we call an anonymous function (as I understand it is exactly what the parentheses do right after {})?

Why when creating libraries (for example for jQuery) we write (function(){ код })(jQuery) ?

Reported as a duplicate by members of Pavel Mayorov , Community Spirit May 16 '18 at 13:29 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Comments are not intended for extended discussion; conversation moved to chat . - YurySPb
  • By the way, a good question is VladD
  • So why did you rediscover the question? There is a third duplicate (which I re-suggested) - it was the exact same! - Pavel Mayorov
  • @PavelMayorov thanks, now I ’ll note - user272575

1 answer 1

IIFE can be called in different ways.
It so happened that usually IIFE is wrapped in brackets; this is necessary in order to make the parser explicitly aware that there will be an expression, not a function declaration.
Otherwise, upon encountering function , the declaration will start parsing:

 (function () { /* ... */ })(); (function () { /* ... */ }()); (() => { /* ... */ })(); // В стрелочных функциях скобки разрешены только снаружи 

Although brackets are optional, these options also work:

 !function () { /* ... */ }(); ~function () { /* ... */ }(); -function () { /* ... */ }(); +function () { /* ... */ }(); void function () { /* ... */ }(); 

If it is clear from the context that there should be an expression here, it is no longer necessary to clearly indicate:

 var f = function () { /* ... */ }(); true && function () { /* ... */ }(); 0, function () { /* ... */ }(); 

Wiki

  • And why is it called immediately? - user272575
  • In the sense of? Why bother with the module? Read then duplicates if you do not know. - user207618
  • Dubli? What is it? - user272575
  • Your question has been closed as a duplicate. And showed that a duplicate of what it is. Here on those links read. - user207618
  • None of the duplicates answers the questions in the question - user272575