What does (function () {}) () mean?

Possible duplicate:
What is the purpose of the self-executing function in javascript?

What tune in JS wrote this code:

(function (window) { })(window);

or that:

(function () { })();
+5
source share
3 answers

It creates a closurepersonal area hiding variables fromglobal object

// Somewhere...
var x = 2;

...
...
// Your code
var x = "foo" // you override the x defined before.

alert(x); // "foo"

But when you use closure:

var x = 2;
// Doesn't change the global x
(function (){ var x = "foo";})();

alert(x); // 2

In terms of syntax, it's just a self-starting function, you declare it and execute it.

+5
source

It is a self-exclusive, anonymous function or function expression. This prevents the creation of variables in a global scope. It also immediately calls a function.

function someFunc() {
    // creates a global variable
}

var someFunc = function () {
    // creates a global variable
}

(function(){
    // creates an anonymous function and 
    // runs it without assigning it to a global variable
})();
+6
source

It is called closure . This helps control the volume of variables, as Javascript raises variables at the top of their area. They are also anonymous functions that are immediately executed or initialized.

+3
source

All Articles