I am in the process of learning JavaScript. While I completely understand that JavaScript does only have function scope and not block scope, I have stumbled accross an example of a for loop in which functions are created completely and I completely ignore why the following example does not work like one would expect it to.
var funcs = [];
for (var i = 0; i < 3; i++) { // let's create 3 functions
funcs[i] = function() { // and store them in funcs
console.log("My value: " + i); // each should log its value.
};
}
for (var j = 0; j < 3; j++) {
funcs[j](); // and now let's run each one to see
}
It outputs this:
My value: 3
My value: 3
My value: 3
And not:
My value: 0
My value: 1
My value: 2
Now I know that the solution would be something like this would be to create a function that returns a function returning the i value which would create a closure for said function.
However, my question is rather, and I have seen a couple of explanations which I don't quite get, why the example does not work in the first place and what is actually happening?
I am unsure how the array func is filled with three keys:
func[0], func[1] and func[2] while the function declaration will always return 3? Why would func[0] even exist in the first place and not only func[3]? It seems to me that there some kind of scope is created in the for loop but only for assigning a key but not for the assignment which I find odd.
Could someone enlighten me? How would a step by step evaluation of the for-loop look like and why?
Thank you very much for your help already!