Explain the difference between the two programs.

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 is always. But let it also have to print everything 3. Explain?

+4
source share
1 answer

The let value is the copied variable. This means that let j puts a unique varibale in a timeout function. Var is a globally variable. This means that var j places the global variable in a timeout function, which is replaced by each for-loop.

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

+3
source

Source: https://habr.com/ru/post/1665993/


All Articles