Difference between closures and IIFE's in javascript

7.4k views Asked by At

According to the Closures concept it will store the variables of the outer lexical environment for future execution of its inner function. For example:

function makeYounger(age) {
    function b() { 
        console.log("Original age is :" + age); 
    }
    b();
    return(function() { 
        return age / 2;
    }); 
}
var displayAge = makeYounger(20); 
console.log(displayAge());

In the above scenario, age is preserved by the Javascript engine to execute the inner function present in the return method.

Here comes the IIFE:

 (function(window) { 
     var greeting = "Hello"; 
     var fNameSpace1 = { 
         name : "Appu", 
         callName : function() { 
             console.log(greeting + fNameSpace1.name);
         } 
     };
     window.doer = fNameSpace1; 
 }) (window);

 fNameSpace1.callName(); //To execute the inner function

In the above scenario according to the closures concept the variables greeting and fNameSpace1.name will be stored for future execution of the callname() function. Instead we are making use of the window object. I am confused why we are going with window if we have closures?

2

There are 2 answers

0
T.J. Crowder On BEST ANSWER

Difference between closures and IIFE's in javascript

An IIFE is just one specific way to A) Create a closure over the context in which it's defined, and B) Create a context in which to create other closures.

My question is what is the exact use of window object in this scenario if the javascript engine already stores fNameSpace1 object.Why are we creating a reference using window?

So it can be used outside the IIFE, by referring to it via the doer global that window.doer = ... creates.

There are dozens of different ways to do this. One of them does it by assigning to window like that. Another does it by returning the value and using a var statement:

var doer = (function() {
   // ...
   return fNamespace1;
})();

but again, there are dozens of different formations. The author of that particular one just preferred to write to a property on window as the way to create the global.

0
chandan kumar On

IIFE is useful to avoid global variable pollution when multiple functions are accessing a global variable

Closure functions are helpful when working with a local variable.