matthewpavkov matthewpavkov - 1 month ago 7
Javascript Question

Difference between closures with parentheses inside vs outside

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() {


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.