0

I just have a curiosity about the difference between using var and let when assigning variables.

for(var i = 0; i < 4; i++){
    setTimeout(() => console.log(i), 1000);
}

output: 4
        4
        4
        4

for(let i = 0; i < 4; i++){
    setTimeout(() => console.log(i), 1000);
}

output: 0
        1
        2
        3

From the above code snippets, I wonder why those two codes log different results.

Jay Jeong
  • 892
  • 2
  • 11
  • 24
  • Because one of the problems `let` is designed to solve is the "closure in loops" problem (see the duplicate Nina tagged). In the second example, a **new** `i` variable is created for each loop iteration; the timeout callback created in that loop iteration closes over the `i` for that iteration, and so sees each individual value (since nothing changes that value). WIth the `var` version, there's only one `i` variable, so naturally all four callbacks show that one variable's value as of when they run. – T.J. Crowder Sep 06 '18 at 07:42
  • mm.. I still not quite get it.. – Jay Jeong Sep 06 '18 at 07:55
  • You've read the third part of [the accepted answer](https://stackoverflow.com/a/750506/157247) to the linked question? – T.J. Crowder Sep 06 '18 at 08:08
  • Yes, I've read it and.. I think I'm getting it, but not 100%. – Jay Jeong Sep 06 '18 at 08:26

0 Answers0