0
var myObject = (function(){

  var value = 0;

  return {
    getValue: function(){
      return value;
    }
  }

}());



var myObject = (function(){

  var value = 0;

  return {
    getValue: function(){
      return value;
    }
  }

})();

The execution seems to return the same Object. i.e., myObject contains

  {{
    getValue: function(){
      return value;
    }
  }}

in both the cases.

I know something like (function(){})() executes because (function(){}) is an expression which returns a function and the trailing () executed the function being returned.

But why does this execute (function(){}()) ? I was expecting a syntax error here.

ShaggyInjun
  • 2,880
  • 2
  • 31
  • 52
  • http://stackoverflow.com/q/4979252/139010 – Matt Ball May 06 '13 at 03:56
  • also fwiw this is syntatically valid because the open paren disambiguates from a function expression (as per [the spec](http://ecma-international.org/ecma-262/5.1/#sec-12.4)), which is why `function(){}()` is a syntax error but `(function(){}())` isn't – kieran May 06 '13 at 04:00
  • Actually `function(){}()` doesn't seem to be an error. I tried this after posting the question. http://jsbin.com/ayujud/1/edit. And I think that essentially means the enclosing `()` are ignored in the first case. Correct me if I am wrong. – ShaggyInjun May 06 '13 at 04:01
  • Both of your examples turn the function definition into a function expression instead of just a function definition. The JS parser needs to know which it is so it doesn't get it wrong. – jfriend00 May 06 '13 at 04:02
  • @ShaggyInjun oh yeah true, the assignment makes it unambiguous, I was just trying a naked `function` call, you're right though – kieran May 06 '13 at 04:05

2 Answers2

5

The phrases are functionally identical, the placement of the () is something of a matter of taste and I've see directions to do either in favour of the other. Personally I prefer

(function() { ... }());

That form, creates the function and executes it inside of the parenthesis.

(function() { ... })();

Creates the function inside of the parenthesis and then executes it.

zellio
  • 31,308
  • 1
  • 42
  • 61
1

They are identical.

As for why (function(){}()) doesn't give a syntax error but function(){}() does, I think it's because the parser, when encountering function will think it is a function declaration rather than a function expression, but then when it sees (), it complains since function declarations have to have a name. But when it sees ( first before function there's no way this is a function declaration, so it thinks it is a function expression.

For (function(){})(), you simply enclosed the function expression in brackets before calling it.

javic
  • 823
  • 1
  • 6
  • 9