We have the following examples that I'm trying to understand:
function makeFunctionArray(){
const arr=[];
for(var i=0;i<5;i++){
arr.push(function(){console.log(i)})
}
return arr;
}
const functionArr = makeFunctionArray();
functionArr[0]();
function makeFunctionArray2(){
const arr=[];
for(let i=0;i<5;i++){
arr.push(function(){console.log(i)})
}
return arr;
}
const functionArr2 = makeFunctionArray2();
functionArr2[0]();
In the first function i is declared with var so has scope of the function. When we return arr each function() in the array is evaluated with i = 5 when the function is executed.
In the second function i is declared with let so the scope of i is now just the for loop. When arr is returned we have an array[0] - arr[4] which each says function(){console.log(i)}. since i is no longer defined when we return arr how is it being evaluated?