Why do these codes have different outputs?
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log("i (first for-loop):", i); // Output: 0 1 2
}, 1000);
}
for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log("i (second for-loop):", i); // Output: 3 3 3
}, 1000);
}
Also, does the setTimeout callback capture the variable by reference, only if it is declared with var?
Thank you