Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between closures with parentheses inside vs outside [duplicate]

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() {
    //...
}());
like image 704
matthewpavkov Avatar asked Oct 23 '13 20:10

matthewpavkov


1 Answers

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.

like image 166
Jacob T. Nielsen Avatar answered Sep 22 '22 17:09

Jacob T. Nielsen