Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does (function () { })();mean? [duplicate]

Possible Duplicate:
What is the purpose of a self executing function in javascript?

What meens in JS write a code like this:

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

or this:

(function () { })();
like image 570
Rodrigo Reis Avatar asked Jul 03 '12 20:07

Rodrigo Reis


2 Answers

It creates a closure, a private scope hiding the variables from the global object

// Somewhere...
var x = 2;

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

alert(x); // "foo"

But when you use a closure:

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

alert(x); // 2

Regarding to the syntax, it's just a self executed function, you declare it and then execute it.

like image 146
gdoron is supporting Monica Avatar answered Oct 22 '22 07:10

gdoron is supporting Monica


It's a self invoking anonymous function or a function expression. It prevents you from creating variables in the global scope. It also calls the function right away.

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
})();
like image 45
Ufuk Hacıoğulları Avatar answered Oct 22 '22 05:10

Ufuk Hacıoğulları