Advanced Concept of "Closures" in Javascript and how it works

//The Advanced Concept of “Closures” Within Java Script and How They Work.

//Lets take a typical function expression and use our knowledge of Immediately Invoked Function Expressions (IIFE) to invoke the function on the fly.

  function greet(whattosay){
      return function(name){
          console.log(whattosay + " " + name);
      }
  }  
    
   greet("Hello  ")("Dollie") //IIFE for both functions generates:
        //**"Hello Dollie"**
        
var sayhi = greet("hi");  //make function a variable

sayhi("Dollie");  //now immediately invoke the 2nd function after calling the first variable. This gives  **"Hi Dollie"**

//This will also return the greet function and invoke the anonymous function with a name. But how did the Java Engine know to attached the name function to the greet function? It is possible because of closures. It saves the memory space used after the execution of the greet function and so its value is still lying there in memory. So it goes up the scope chain and “closes” the outer environment variables. The Java Script engine therefore still has access to the outer environment variables.

//Now lets take a classical case that you will find on-line in understanding what’s under the hood of the Java Script Engine//

function buildFunctions(){
var arr = [ ]; //set up an array

for (var i =0; i < 3; i++){
    
    arr.push(function(){
        console.log(i);   //push the same function into the array until i =<3 //
    }
   )
}
return arr;         //return value of array

}

var fs = buildFunctions(); // change function to variable

fs0; // invoke each function in the array to console.log(i)
fs1;
fs2;

//What do you expect to see when we invoke the function? Not what some would expect. You will get 3, 3, 3. Did you expect this? Remember we do not invoke the function until we call the function. So for each new function we add with the for loop, “i” will increase from 0 to 3 before the “arr” is returned. So the value of “i” is “3” for each of the functions in the array since that is the value of “i” after the for loop has completed itself. So when we execute the function then we want to know how old your father(i) is now, not at the time you were born. So all three give the same result.

//Now how would we get the result you might have expected which is how do we get the “i” at the time the function was created in the array. Well with the new Java Script ES6 you can use the “let” statement which keeps the context of the variable within the block.

function buildFunctions1(){
var arr = [];

for (var i =0; i < 3; i++){
    let j = i       //set j = i to store the value of "i" each time a function is pushed into the array
    arr.push(function(){
        console.log(j);  //print the value of "j" at the time of function creation.//
    }
   )
}
return arr;

}

var fs1 = buildFunctions1();

fs10;
fs11;
fs12;

//Now this will return the value of “i” for each time a function is added to the array and you will get 0,1,2. as a result.

// Now if you are using Java Script ES5 we have to add another function to hold the value of “i”. So we do an immediately invoked function to give the value of “i” at the time each function is created in the array. And we use “j” as the parameter of the new functions and call or invoke the function by using the value of “i” so that j = i, each time that a function is added to the array. And before be go to the next step in the for loop we return the new function performing console.log the value of “j”.

function buildFunctions2(){
var arr = [];

for (var i =0; i < 3; i++){
    
    arr.push(
        (function(j){
            return function(){
                console.log(j);
            }
        }(i))
   )
}
return arr;

}

var fs2 = buildFunctions2();

fs20;
fs21;
fs22;

//Again this will return the value of “i” for each time a function is added to the array and you will get 0,1,2. as a result. If you understand Closures then you understand Advance Java Script basics. Play with this a while until it makes sense. Enjoy!!

1 Like

These are really advanced topics. Keep up the good work.

Excellent explanations!

Cheers. :smile:

1 Like