0

I have two codes. In my opnion, they are the same, but I got different outputs. Can someone help me!

Code 1:

for (let i=0;i<=1;i++)
{
    setTimeout(()=>{console.log(i)},1000)
}
//output: 0 1

Code 2:

{
    let i=0
    {
        setTimeout(()=>{console.log(i)},1000)
    }
    i++
    {
        setTimeout(()=>{console.log(i)},1000)
    }
}
//output: 1 1
jack
  • 21
  • 2
  • 1
    They are not the same? The second is not a for loop. – evolutionxbox Jul 14 '22 at 08:15
  • What were you expecting to happen? – phuzi Jul 14 '22 at 08:15
  • 3
    They are different. In a for loop, `let i` creates a separate binding for the `i` in each iteration [refer to the answer in https://stackoverflow.com/a/30900289/4225384 ]. In your second code, the `i` is shared within its scope. – qrsngky Jul 14 '22 at 08:17
  • 1
    This also feels rather similar to all those async questions that keep popping up. It has to do with who and what `i` is at the time, and who and what defined it. Read up on docs for `for` to see whats going on. – somethinghere Jul 14 '22 at 08:20
  • Thanks @qrsngky, I think i have understand this problem now! – jack Jul 15 '22 at 01:03

1 Answers1

-2

In code 1: You set i = 0 and execute setTimeout in a loop, so the timeouts get the value that is i on each loop, resulting in 0, 1:

  1. i=0
  2. console.log
  3. i=1
  4. console.log

In code 2: You set i = 0, execute setTimeout, and because you dont have on restriction when to increment i, so it gets incremented instantly since setTimeout is asynchronous, and then your setTimeout functions run after that resulting 1,1.

  1. i=0
  2. i=1
  3. console.log
  4. console.log
Tarmo U
  • 1
  • 1
  • 1
    This is not how the first block works, setTimeout is essentially asynchronous and execution of the loop is completed before even the first setTimeout has been triggered. Your explanation of the second code applies equally to the first code. – phuzi Jul 14 '22 at 08:23
  • Yeah you're correct, I missed my point there, that the timeouts get different values since they are executing in the loop that increments it. Corrected the answer. – Tarmo U Jul 14 '22 at 08:40
  • Almost, the question is really about the difference between `var` and `let` in the for loop and the scope of these. – phuzi Jul 14 '22 at 08:50
  • 1
    Oh wow, I focused on the "they are the same, but I got different outputs. Can someone help me!" - part and not the title, this was a trainwreck of an answer :D – Tarmo U Jul 14 '22 at 09:06
  • No worries, done this myself so many times and ended up deleting my answer as a result. – phuzi Jul 14 '22 at 09:08