Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange JavaScript syntax like this: (function(){//code}) ();?

What does the below JavaScript mean? Why is the function embedded inside ()?

(function() {
    var b = 3;
    a += b;
}) ();
like image 227
Jeff Avatar asked Aug 27 '09 12:08

Jeff


1 Answers

It's functionaly equivalent to doing something like:

var myFunc = function(){
    var b = 3;
    a += b;
};

myFunc();

It's got the parenthesis around it (and trailing) so that the function is called immediately. As others have said, the concept is called an anonymous function.

like image 70
Justin Niessner Avatar answered Oct 11 '22 22:10

Justin Niessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!