0

I have a question about how the let scope work in a for loop, regarding the following examples.

for(let i=0;i<5;i++){
    setTimeout(()=>{
  console.log(i);
  },1000)
}
// will print out 0,1,2,3,4
for(var j=0;j<5;j++){
    setTimeout(()=>{
  console.log(j);
  },0)
}
// will print out 5,5,5,5,5

I know the difference between var and let. The var has a function scope and the let has a block scope.
For the let one, though the i is inside the for loop, the console.log(i) always take in the same variable i. The variable i is updated in each iteration. So when the setTimeout callback functions are executed, they have the same i, and they should print the same number, which is 5 here.
The var and let have different scope, but both are updated in each iteration, and both variables are logged at the end. Shouldn't they have the same result?

combo combo
  • 85
  • 1
  • 7
  • 2
    https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – epascarello Apr 05 '21 at 20:38
  • There is an additional layer of scoping here with the fat arrow `() => {}` construct. This creates what is called a "closure". I suggest you google "javascript closure" or something similar to learn more about how it works. – Code-Apprentice Apr 05 '21 at 20:40
  • 1
    "*the `console.log(i)` always take in the same variable `i`*" - no, it doesn't. Every closure closes over a different variable `i`, as - as you say - it is created inside the loop. – Bergi Apr 05 '21 at 20:40
  • @Code-Apprentice I think he understands closures. What wasn't clear is that there's a separate scope for each iteration of the loop, not a single scope for the entire loop. – Barmar Apr 05 '21 at 20:41
  • 1
    @Barmar Yes, I understand closures. Thanks for your keyword _separate scope_. I found another question about it https://stackoverflow.com/questions/59170277/javascript-understanding-let-scope-inside-for-loop. Now I know the `i` are different variables in each iteration. – combo combo Apr 05 '21 at 21:18

0 Answers0