Setting up the variable i
before the for loop will result in the output being 3 3 3.
let i;
for (i = 0; i < 3; i++) {
const log = () => {
console.log(i);
}
setTimeout(log, 100);
}
//Output 3 3 3
If i
is declared within the for loop, the output will be 1 2 3:
for (let i = 0; i < 3; i++) {
const log = () => {
console.log(i);
}
setTimeout(log, 100);
}
//Output 1 2 3