What is the correct fix?
var fns = [];
for (var i = 0; i < 3; i++) {
fns.push(() => i);
}
console.log(fns.map(f => f()));
- Change
() => ito() => i++ - Use
fns[i] = i - Move the push outside the loop
- Change
var itolet i
let gives each iteration its own i; var shares one.