var funcs = ;
// let’s create 3 functions
for (let i = 0; i < 3; i++) {
// and store them in funcs
funcs[i] = function() {
// each should log its value. return "My value: " + i;
};
}
for (var j = 0; j < 3; j++) {
// and now let’s run each one to see
console.log(funcsj)}
I have this piece of code. I know that this will print all values and not only 3 like with var. Each of the func[j] has the value "function(){// each should log its value. return"My value: “+i;}”. Why when you run func[0] it knows what it should be printed when you do return "My value: " + i;? I understand that var will keep the value after exiting the loop (3) and will print it each time, but how does javascript knows what i to print when using let? I mean what happens when you actually call func[0]? I understand that we create a scope for each i, but how does actually knows when you call func[0] to actually use that scope for i =0 in order to return correct value?