8

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 () { })();
Community
  • 1
  • 1
Rodrigo Reis
  • 1,097
  • 12
  • 21
  • It's a duplicate so I voted to close, though I think the answers there aren't as good as the answers here. specially not [this wrong +17 answer](http://stackoverflow.com/a/592411/601179) – gdoron Jul 03 '12 at 21:14
  • If someone looks for PHP 7, where this has been introduced. https://stackoverflow.com/questions/3568410/how-do-i-immediately-execute-an-anonymous-function-in-php – Franz Holzinger Nov 15 '19 at 15:12

3 Answers3

12

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.

jao
  • 18,273
  • 15
  • 63
  • 96
gdoron
  • 147,333
  • 58
  • 291
  • 367
7

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
})();
Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156
3

It's called a closure. It helps control the scope of variables since Javascript hoists variables to the top of their scope. They're also anonymous functions which execute or initialize immediately.

Community
  • 1
  • 1
Matt
  • 22,721
  • 17
  • 71
  • 112