matthewpavkov matthewpavkov - 1 year ago 93
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() {

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download