4
for (let j=0; j<3; j = j+1) {
    setTimeout(function() {
      console.log(j);
    }, 1000);
}

output 0 1 2

for (var j=0; j<3; j = j+1) {
     setTimeout(function() {
         console.log(j);
     }, 1000);
}

output 3 3 3

I understand why using var prints 3 always. But even let also should print all 3. Explain?

Sudhir
  • 89
  • 1
  • 4

1 Answers1

3

The let is a scoped variable. That means the let j put a unique varibale in the timeout function. The var is a globally variable. That means the var j put a global variable in the timeout function that is replaced by every for-loop.

Here is the explanation: What's the difference between using "let" and "var" to declare a variable?

Community
  • 1
  • 1
DomeTune
  • 1,401
  • 10
  • 21