2

Possible Duplicate:
What does this “(function(){});”, a function inside brackets, mean in javascript ?

(function(){
    ---this code at here ----
})();

What does (function(){})(); mean? Please explain it to me.

Community
  • 1
  • 1
meotimdihia
  • 4,191
  • 15
  • 49
  • 69
  • 1
    duplicate: http://stackoverflow.com/questions/4043647/what-does-this-function-a-function-inside-brackets-mean-in-javascript – fazo Mar 04 '11 at 10:03

3 Answers3

5

It makes an anonymous function and executes it. You use it to prevent variables from poluting the global scope.

(function(){
  var test = "Hello";
})();

alert(test); //test will be undefined here
Decko
  • 18,553
  • 2
  • 29
  • 39
4

The function is immediately executed after parsing it.

TurBas
  • 1,646
  • 13
  • 15
  • ok, what is the reason to put it in a function body then, rather than just writeing its code within the script tags? – Nickolodeon Apr 12 '12 at 07:27
0

Well, you use a function expression as a closure which gets executed immediately and 'this code at here' will not pollute global namespace.

Torsten Becker
  • 4,330
  • 2
  • 21
  • 22