JavaScript - What is the difference between let and var in a for loop?

25 views Asked by At

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

0

There are 0 answers