IIFE

Ayush
1 min readApr 24, 2017

--

IIFE is termed as Immediately Invoked Function Expression. Sometimes you need to call the function, just after it’s definition. IIFE is the approach which can be very helpful in this case.

To understand IIFE, Let’s take an example:

var results = [];var i;for (i = 0; i < 5; i += 1) {  results.push(function(){ return i; });}// Now calling the function.console.log(results[2]()) // outputs 5console.log(results[3]()) // outputs 5console.log(results[4]()) // outputs 5

Here, Closures keep their connections to outer variables. The value returned in above example is always the current value of i which is 5.

Introduction of IIFE

It is a pattern for using a function in a block-like manner. Let’s take a look at IIFE’s syntax :

(function(){   var temp;}())

here, temp is in the local scope of function. Now in above example, If you want to receive always the current value of i, the function can rewritten as in IIFE:

var results = [];var i;for (i = 0; i < 5; i += 1) {  ( function () {     var i2 = i;     results.push( function () { return i2; })  } ())}console.log(results[2]()) // outputs 2console.log(results[3]()) // outputs 3console.log(results[4]()) // outputs 4

JS FIddle Demo

--

--