Reputation: 384
Simple, why do some js files (such as Ember or JQuery.js) begin with (function() {...})();
?
Upvotes: 19
Views: 8872
Reputation: 324750
Code of the form (function() { /* code here */ })()
is known as an "Immediately Invoked Function Expression". It is frequently used to set up a closure, so you can define variables without polluting the global scope. You find it in Ember, jQuery, and pretty much every other "plug-in" for this reason. Polluting the global scope is generally a bad idea, but with plug-ins that must work on all sites it is especially important to make sure it doesn't accidentally overwrite a variable the site's creator is using.
Of course, there are other uses. For instance, it can be used to "anchor" an iterating variable, like so:
for( i=0; i<links.length; i++) {
(function(i) {
links[i].onclick = function() {alert(i);};
})(i);
}
// without the IIFE, all links would alert the value of links.length instead.
There are also some cases I occasionally use IIFEs that most people would probably lynch me for, such as a "just-in-time" computation:
if( (function() {
var party=document.getElementById('party').children, l=party.length, i, r=0;
for( i=0; i<l; i++) if( party[i].children.length > 0) r++;
return r;
})() == 6) {
// your Party is full
}
The above would be much better if it were calculated before jumping into the if
statement, so... do not do as I do on this one!
Upvotes: 21
Reputation: 1446
The syntax started with
(function(){
/* code */
}());
knows as Immediately invoked anonymous function which executes immediately after last line of code. Used for scoping variables of other functions.
For more: http://en.wikipedia.org/wiki/Immediately-invoked_function_expression
Upvotes: 8