Member-only story
Scoping in JavaScript For Loops
let vs. var inside your loop
I stumbled over two code snippets that made me think about the scoping in for loops and about a possible misunderstanding. The first one looks as follows:
You can see it from time to time to demonstrate the event loop, the concept of closures, or as an interview question. The output of that code is:
3
3
3
The variable i
is captured in the closure of the anonymous function that calls console.log()
and is invoked asynchronously via setTimeout()
. So the invocation is added to the event loop, and at the time of invocation, the captured variable i
has already been incremented to 3.
So far, so good. But what about the following code?
The output is:
0
1
2