Immediately-Invoked Function Expression (IIFE)

Scope in Javascript is function-bound, meaning variables defined in a function are visible inside the same function, and each time a function is invoked it creates a new execution context. This is different from C which confines life span of variables inside a block. For following code:

var a = 1;

function f1() {
  var b = 2;
  console.log('inside f1 a:'+a);
}

function f2() {
  var c = 3;
  return function(d) {
    return d+c;
  }
}

{
var e = 5;
}

f1();

console.log(a);
console.log(b); //error
console.log(e);
console.log(f2()(4)); //closure

Only hidden variable to the global context is b. Since every C function is defined using block Javascript is more loose in the sense that blocks without function declaration doesn’t really do much.

Now move on to Immediately-Invoked Function Expression: the motive behind this is you want to execute a piece of code without contaminating the global context while being able to use many of the global variables. You do it by creating an anonymous function and immediately invoking it:

(function () {
 ...
})();

This is a very common pattern for Javascript and is seen everywhere, especially for locking in the value of
execution context. More reading can be found at http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Leave a comment