Better Programming

Advice for programmers.

Follow publication

Member-only story

Scoping in JavaScript For Loops

Johannes Baum
Better Programming
Published in
2 min readApr 28, 2020
Photo by Mika Korhonen on Unsplash

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

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Johannes Baum
Johannes Baum

Written by Johannes Baum

Creator of GridEngine (https://github.com/Annoraaq/grid-engine) 👾 Software Engineer 🚀 JavaScript/TypeScript

Write a response