I’m encountering a puzzling issue with JavaScript where the loop variables are not functioning as I expect. This is what I am attempting to do:
var callbacks = [];
// creating 5 callback functions
for (var x = 0; x < 5; x++) {
callbacks[x] = function() {
console.log("Current number:", x);
};
}
// executing each callback
for (var k = 0; k < 5; k++) {
callbacks[k]();
}
However, instead of getting:
Current number: 0
Current number: 1
Current number: 2
Current number: 3
Current number: 4
I instead receive this output:
Current number: 5
Current number: 5
Current number: 5
Current number: 5
Current number: 5
The same issue arises when I use click handlers:
var links = document.querySelectorAll('a');
for (var x = 0; x < links.length; x++) {
links[x].onclick = function() {
console.log("Link index:", x);
};
}
<a href="#">First</a>
<a href="#">Second</a>
<a href="#">Third</a>
This also occurs with asynchronous actions:
const delay = (time) => new Promise(resolve => setTimeout(resolve, time));
for (var x = 0; x < 3; x++) {
delay(x * 50).then(() => console.log(x));
}
It even happens with various loop types:
const numbers = [10, 20, 30];
const handlers = [];
for (var idx in numbers) {
handlers.push(() => console.log("position:", idx));
}
for (var val of numbers) {
handlers.push(() => console.log("amount:", val));
}
for (const item of numbers) {
var record = { value: item };
handlers.push(() => console.log("item:", item, "record:", JSON.stringify(record)));
}
handlers.forEach(h => h());
What can I do to resolve this common predicament?