Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this? (function(){ })() [duplicate]

Possible Duplicates:
What does this JavaScript snippet mean?
Location of parenthesis for auto-executing anonymous JavaScript functions?

(function(){

    //something here...

})() <--//This part right here.

What exactly is this )()?
What if I change it to this ())?

(function(){

    //something here...

}()) <--//Like this
like image 489
Derek 朕會功夫 Avatar asked Jul 21 '11 22:07

Derek 朕會功夫


1 Answers

This declares an anonymous function and calls it immediately.

The upside of doing this is that the variables the function uses internally are not added to the current scope, and you are also not adding a function name to the current scope either.

It is important to note that the parentheses surrounding the function declaration are not arbitrary. If you remove these, you will get an error.

Finally, you can actually pass arguments to the anonymous function using the extra parentheses, as in

(function (arg) {
   //do something with arg
})(1);

See http://jsfiddle.net/eb4d4/

like image 52
Explosion Pills Avatar answered Oct 13 '22 13:10

Explosion Pills