7

Can someone explain what the difference is between these closures? Is there a difference? I haven't previously seen the second example (parentheses inside).

(function(a, b) {
    //...
})(x, y);

// Parentheses inside
(function(a, b) {
    //...
}(x, y));

And here, is there a difference between these closures? Is there a scenario where there would be a difference?

FOO.Bar = (function() {
    //...
})();

FOO.Bar = (function() {
    //...
}());
matthewpavkov
  • 2,918
  • 4
  • 21
  • 37
  • That's not a closure, that's an [IEFE](http://benalman.com/news/2010/11/immediately-invoked-function-expression/). It might return a closure, but that's not relevant here. – Bergi Oct 23 '13 at 20:23
  • exact duplicate of [Location of parenthesis for auto-executing anonymous JavaScript functions?](http://stackoverflow.com/questions/3384504/location-of-parenthesis-for-auto-executing-anonymous-javascript-functions) or [Is there a difference between (function() {…}()); and (function() {…})();?](http://stackoverflow.com/questions/3783007/is-there-a-difference-between-function-and-function) – Bergi Oct 23 '13 at 20:28
  • @Bergi Thanks for the clarification and link. It seems I need to do a bit more reading. – matthewpavkov Oct 23 '13 at 20:30

1 Answers1

2

No. In both cases they are exactly the same.

What happens when you wrap your function in parentheses is that is goes from a function declaration to a function expression, which can be invoked immediately.

Whether you invoke it within the parentheses or after does not matter. The "convension" has happened and you can thus invoke it.

And actually you can do this

FOO.Bar = function () {
    return 123;
}();

The above is already a function expression since you are assigning an anonymous function to a property Bar on FOO.

JJJ
  • 32,902
  • 20
  • 89
  • 102
Jacob T. Nielsen
  • 2,938
  • 6
  • 26
  • 30
  • Jacob, wouldn't the OP be better off with the top two approaches, because they can be placed anywhere in his script and still reference data above or below the closure? - just asking... – klewis Oct 23 '13 at 20:13
  • Well that depends. It do not think he is comparing the first two with the second two. In any case that would not make sense. The second two should return a value that could be assigned to FOO.Bar. The first two don't indicate any value being returned. Usually just for scoping something. – Jacob T. Nielsen Oct 23 '13 at 20:19
  • I didn't intend to compare the first 2 code examples with the second 2. Thanks for the info. – matthewpavkov Oct 23 '13 at 20:34