Help about functions in general: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions.

Help about IIFE in detail: http://benalman.com/news/2010/11/immediately-invoked-function-expression/

When you define a function like this:

(function() {
    statements
})();

this is a function expression that is invoked as soon as the function is declared! Benefits:

  • It does not pollute the current scope.
  • Variables are locked in, e.g. variables defined inside the function stay in the functions are cannot be accessed from outside.
  • Javascript has function scope, so when you define something inside a function, it is only valid inside this function.

 

Module pattern in Javascript

The module pattern uses IIFE to return the functions return value. Idea:

var module = (function() {
  var i = 0;
  return {
     ...
  };
})();
 
// Now module references the returned object, and the variable i is private to this instance of "module"

or, with a full example

var counter = (function(){
  var i = 0;
 
  return {
    get: function(){
      return i;
    },
    set: function( val ){
      i = val;
    },
    increment: function() {
      return ++i;
    }
  };
}());
 
counter.get(); // 0
counter.set( 3 );
counter.increment(); // 4
counter.increment(); // 5
 
counter.i; // undefined (`i` is not a property of the returned object)
i; // ReferenceError: i is not defined (it only exists inside the closure)