1
 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?

Kashif Ali
  • 187
  • 2
  • 9
  • To undestand it you need to read about synchronous and asynchronous functions and how it works in Javascript. And then you need to learn about let and var scope/Hoisting. – Alyf Mendonça May 13 '22 at 18:59

0 Answers0