for(var i = 0; i < 10; i++) {
console.log(i);
setTimeout(function() {
console.log(`The number is ${i}`);
}, 1000);
}
This above block of code log 0-9 correctly but then prints “The number is 10” ten times instead of printing “The number is 0”, “The number is 1” and so on
However, if I change the variable declaration to ‘let’. Then it prints out correctly.
for(let i = 0; i < 10; i++) {
console.log(i);
setTimeout(function() {
console.log(`The number is ${i}`);
}, 1000);
}
This above block of code prints the statements correctly. Each statement is printed after a delay of one second like “The number is 0”, “The number is 1” and so on.
I’m not able to understand what is going on here. Can someone break it down for me?