The difference between var foo = function () {...} () and var foo = (function () {...} ())

I am working on an existing project that has been encoded by some developers that I don’t know. Surfing on javascript files, I see that they use this particular notation for the define function:

var ModuleScripts = (function() {
  return {
    init: function(){...}
  };
}())

Note in parenthesis function(){...}(). This code works fine, but when I want to write something, I use this notation:

var ModuleScripts = function() {
  return {
    init: function(){...}
  };
}()

My code is working fine. So my question is: is there any good reason to use parentheses surrounding function(){...}()JavaScript?

+4
source share
2 answers
+4

IIFE, ModuleScripts init(). IIFE ModuleScripts - , ! IIFE , , , , .

(!) IIFE, , , IIFE . , , . .

IIFE :

(function() {
  // the code here is executed once in its own scope
})();

:

var ModuleScripts = (function() {
  return {
    init: function(){...}
  };
}())

IFFE

(function x(){})()

(  function x(){}()  )
+1

Source: https://habr.com/ru/post/1619523/


All Articles