I have the following small code snippet with the following expected and real output. My question is quiet simple. Why is it printing it this sequence? and how to I print the expected output?
Gr,
expected result:
0
1
2
0
1
2
real result:
0
1
2
3
3
3
this is the code:
var functions = [];
for (var i=0; i<10; i++) {
console.log (i);
functions.push (function () {
console.log (i);
});
};
for (var j=0; j<functions.length; j++) {
functions[j] ();
};
The functions that you push into the array doesn’t log the value of
ias it was when the function was created, they log the value ofiat the time that the function is called.Once the first loop ends, the value of
iis10, therefore any of the functions called after that will log the value10.If you want to preserve the value of
iat different states, you can use a closure to make a copy of the value:The local variable
copywill get the value ofiand retain the value. You can also pass the value as a parameter to the function: