⏱ 0:01est. 5 min
Chapter 47- Understanding Closures (Part 2)
Notes
Example 1
function buildFunctions(){
var arr = [];
for(var i =0 ;i <3;i++){
//creating the function, not executing
arr.push(
function(){
console.log(i);
}
)
}
return arr;
}
var fs = buildFunctions();
//executing the functions
fs[0]();//3
fs[1]();//3
fs[2]();//3
//Why -
Global execution context is always there buildFunctions(), fs
When buildFunctions get invoked we get arr [f0,f1,f2] and i 3
After this buildFunctions execution context is popped off the stack
fs[0]() execution context is created there is no variable i inside the scope so it goes up the scope chain if finds i = 3 hangging around then fs[1]() and then fs[2]() also has same outer environment reference
Overcoming this problem
function buildFunctions2(){
var arr = [];
for(var i =0 ;i <3;i++){
//the only way to get execution context of i in function is by executing the function
//creating the function, not executing
arr.push(
//IIFE - immediately invoke function expression
(function(j){
console.log(j);
}(i))
)
}
return arr;
}
function buildFunctions2(){
var arr = [];
for(var i =0 ;i <3;i++){
arr.push(((j) => {
return () => console.log(j)
})(i))
}
return arr;
}
var fs2 = buildFunctions2();
//executing the functions
fs2[0]();//1
fs2[1]();//2
fs2[2]();//3