The loop closure bug is when creating an array of functions inside of a loop that references i
, the end result for all the functions is the same value of i
.
for (var i = 0; i < 3; i++) { funcs[i] = function() { console.log("My value: " + i); }; } // outputs: // My value: 3 // My value: 3 // My value: 3
One possible solution is to use let
instead. By using let
instead, a new i
variable exists on each iteration, so the code works as expected. Using var
means that i
is bound to the same variable outside of the loop. Each function would print 3
as i
exists outside of the scope of the loop, and is not 'captured' at any point of time. This also means setting i
after this loop and before calling funcs
would also change the output.
[[20210426173817-block-scoping-js]]
Another solution is to create a closure that creates functions. This function will make its own local copy of the variable. (TODO)
function createFunc(i) {
return function() {
console.log("My value: " + i);
};
}
for (var i = 0; i < 3; i++) {
funcs[i] = createFunc(i);
}
TODO - link to closures doc