Alex Rivera | Logout

What is the (function() { } )() construct in JavaScript?

Asked 2011-11-22T14:19:11.947
959

I would like to know what this means:

(function () {

})();

Is this basically saying document.onload?

Edit
Report

1 Answer

34

That is saying execute immediately.

so if I do:

var val = (function(){
     var a = 0;  // in the scope of this function
     return function(x){
         a += x;
         return a;
     };
})();

alert(val(10)); //10
alert(val(11)); //21

Fiddle: http://jsfiddle.net/maniator/LqvpQ/


Second Example:

var val = (function(){
     return 13 + 5;
})();

alert(val); //18
answered 2011-11-22T14:21:29.013

Your Answer