What you can expect as the result is:
1
2
...
10
10
10
... repeated 7 more times
The explanation for this outcome is quite straightforward. The console.log(i)
statement within your loop correctly displays the value of i
at each iteration. However, when you create and add a function to the functions
array, you are effectively encapsulating all those functions over the same variable i
. As the loop reaches its end, i
no longer meets the loop condition, making i = 10
true. Consequently, since every one of these functions will execute console.log(i)
, and they are all enclosed over the same shared i
which now holds the value of 10, you should anticipate seeing the number 10 printed ten times.
To mitigate this issue, it's advisable to create a function that returns another function rather than producing functions directly in a loop:
var functions = [], i, j;
function createEmitter(i) {
return function () {
console.log(i);
};
}
for (i = 0; i < 10; i++) {
console.log(i);
functions.push(createEmitter(i));
};
for (j = 0; j < functions.length; j++) {
functions[j]();
};
By following this approach, each newly created function will be confined within its own individual scope, effectively resolving the issue at hand.