1

Can someone explain to me this:

function f(){
    for(var i=0; i<4; i++){
        setTimeout(()=> {console.log(i)}, 0);
    }
    console.log('test');
}

When I call this function it returns: test 4 4 4 4, but when I write LET instead of VAR it returns test 0 1 2 3.

Now I am familiar with why test is printed first, and with the under the hood concepts. But I just dont know why it is this way...

untitled
  • 119
  • 3
  • 1
    With `var`, there's only **one** `i` variable, and your timeout callbacks see its value (4) as of when they run. With `let` in a `for` loop, a **different** `i` variable is created for each loop iteration, and each callback closes over the one for the loop iteration that created it, so you see their values (0, 1, 2, and 3). (FWIW, I go over this in detail in Chapter 2 of my recent book, links in my profile.) – T.J. Crowder Apr 08 '22 at 15:27
  • 1
    `var` is scoped to the `f` function so is shared by all the callback functions. By the time any of the callback functions are triggered, it is `4`. `let` is scoped to the block so each callback gets a unique `i` variable. – Quentin Apr 08 '22 at 15:27
  • 1
    `let` is block-scoped but that's only half of the explanation, because if you'd put the `let` statement outside of the `for`, it won't work, but then the question is where does the scope really start, given that `i++` must still work? It is actually a lot more complicated than that. Good explanation here: https://youtu.be/Nzokr6Boeaw – CherryDT Apr 08 '22 at 15:53

0 Answers0