Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between closures and IIFE's in javascript

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?

like image 718
CodeForHappiness Avatar asked Mar 27 '26 00:03

CodeForHappiness


2 Answers

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.

like image 72
T.J. Crowder Avatar answered Mar 29 '26 13:03

T.J. Crowder


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.

like image 28
chandan kumar Avatar answered Mar 29 '26 14:03

chandan kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!