4

I have been working on an existing project that was coded by some developers that I do not know. Surfing on javascript files, I see that they use this specific notation for define function:

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

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

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

My code works perfectly too. So my question is: Is there a good reason to use parenthesis surrounding function(){...}() in JavaScript?

Daniel Batalla
  • 1,184
  • 1
  • 11
  • 22
  • Possible duplicate: http://stackoverflow.com/questions/1634268/explain-javascripts-encapsulated-anonymous-function-syntax – AtheistP3ace Dec 11 '15 at 15:33
  • Both do the same thing, it's just a different way of writing it. Both functions are immediately invoked. – Nick Snick Dec 11 '15 at 15:35
  • possible dupe: http://stackoverflow.com/questions/3384504/location-of-parenthesis-for-auto-executing-anonymous-javascript-functions – Hitmands Dec 11 '15 at 15:37

2 Answers2

4

From Immediately-invoked function expression:

Immediately-invoked function expressions may be written in a number of different ways, although a common convention is to enclose both the function expression and invocation in parentheses.

sp00m
  • 47,968
  • 31
  • 142
  • 252
1

If it was an IIFE, it would immediately execute and ModuleScripts would be an object with an init() function. Without an IIFE, ModuleScripts is a function that returns an object! A lot of the time IIFEs are used to protect namespaces, and it seems they were trying to do that here, but didn't do it right.

(!) At first glance it looks like an IIFE, but actually I think the parenthesis in your example are different from an IIFE, and are just thrown out. So you'd end up seeing them do nothing. Note the difference.

IIFE Immediately-invoked function expression:

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

Your example:

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

More simply put an IFFE is

(function x(){})()

and you are seeing

(  function x(){}()  )
Daniel Batalla
  • 1,184
  • 1
  • 11
  • 22
spozun
  • 872
  • 1
  • 6
  • 14