19

Simple, why do some js files (such as Ember or JQuery.js) begin with (function() {...})(); ?

the12
  • 2,395
  • 5
  • 19
  • 37
Makerimages
  • 384
  • 6
  • 27
  • Here is one relevant SO question: http://stackoverflow.com/questions/1140089/how-does-an-anonymous-function-in-javascript-work. This should, imo, be closed as a duplicate. – Justin Blank Oct 10 '13 at 13:28
  • 4
    This question is not a duplicate, and has nothing with the referenced question, as the referenced question doesn't ask what is the purpose of a closure as in this post, instead the referenced question asks why the invocation must be in the same line as the declaration – yoel halb Dec 03 '14 at 00:24

2 Answers2

21

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!

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
8

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

Prakash Bhagat
  • 1,406
  • 16
  • 30