Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 13

Solving the Loop-Closure Bug

Recommended resources

Welcome back. In our last lesson, we established a robust mental model for how closures work in memory: a function object carries a "backpack" (a reference via its [[Environment]] slot) containing its creation-time lexical environment, keeping that environment alive on the heap.

Today, we'll put that model to the test by diagnosing and fixing one of the most classic and revealing JavaScript interview questions: the loop-closure bug. This isn't just a "gotcha"; it's a diagnostic tool that separates developers who know a pattern from those who understand the underlying mechanics of scope, memory, and timing. By the end of this lesson, you'll be able to not only solve the problem in multiple ways but also articulate precisely why each solution works, a hallmark of a senior engineer.

The Classic Loop-Closure Bug

[Always asked]

Let's start with a snippet of code that has tripped up countless developers. Before reading the explanation, predict what this code will log to the console.

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

Most people intuitively expect the output to be 0, 1, 2. However, the actual output is 3, 3, 3.

Why? This behavior is a direct consequence of the concepts we covered in the last lesson. Let's break it down:

  1. Shared Environment: The var keyword declares i in the function scope (or global scope, in this case). This means there is only one i variable that all three setTimeout callbacks share. Their [[Environment]] references all point to the same lexical environment.

  2. Synchronous Loop, Asynchronous Callbacks: The for loop itself runs to completion synchronously. It iterates, queues up three setTimeout callbacks, and finishes. By the time it's done, the single i variable has been incremented to 3.

  3. Callback Execution: Much later (after 100ms), the event loop picks up the first callback from the macrotask queue and executes it. The callback needs to resolve the value of i. It looks in its "backpack" (its closure) and finds the reference to i. It then logs the current value of that i, which is 3. The same happens for the next two callbacks. They all reference the same final value of the same variable.

This isn't limited to setTimeout. As the following resource shows, the same bug appears with event handlers and other asynchronous operations.

Loop variable closure issue in JavaScript - why functions capture wrong values - JavaScript - Latenode Official Community

This community post provides clear, concise examples of the loop-closure bug in different contexts.

Read the initial question, which showcases the problem with an array of functions, event handlers, and async operations. Notice how the root cause is the same in every case.

Now, let's dissect the three primary ways to fix this.


Solution 1: let - The Modern Fix

The simplest and most common solution in modern JavaScript is to replace var with let.

for (let i = 0; i < 3; i++) {
  setTimeout(() => {
    console.log(i);
  }, 100);
}
// Correctly logs: 0, 1, 2

This works, but a senior developer must explain why it works beyond just saying "block scope." The key is a special behavior of let (and const) in the header of a for loop.

According to the ECMAScript specification, when a for loop with a let declaration is evaluated, it doesn't just create one variable. Instead, for each iteration of the loop, it creates a new lexical environment and a new binding for i within that environment, initialized with the value from the previous iteration.

This means:

  • Iteration 1: A new scope is created. i is 0 in this scope. The first callback closes over this specific scope.
  • Iteration 2: A different new scope is created. i is 1 in this scope. The second callback closes over this scope.
  • Iteration 3: A third new scope is created. i is 2 in this scope. The third callback closes over this scope.

Each callback function gets its own "backpack" containing its own unique i. They don't share a single i anymore.

The following Stack Overflow answer provides an excellent, spec-level explanation of this mechanism.

javascript - Behavior of let variables declared inside for loop in context of closures - Stack Overflow

This is the deep dive. It explains the engine-level behavior of let in loops.

In the accepted answer, read the explanation that references the ECMAScript standard. Focus on the part that describes the ForBodyEvaluation and CreatePerIterationEnvironment steps. The key takeaway is in the final sentence: this is why it works.

When you debug this code, you can see this separation in the browser's DevTools. The "Scope" panel will show a Block scope containing the i specific to that callback's iteration.

An example of what a closure looks like in Chrome DevTools. The `Closure` section in the scope panel reveals the variables retained in the function's "backpack", linking the theoretical concept to a practical debugging view.

Solution 2: IIFE - The Classic (Pre-ES6) Fix

Before let was introduced in ES6, the standard way to solve this was with an Immediately Invoked Function Expression (IIFE).

for (var i = 0; i < 3; i++) {
  (function(captured_i) {
    setTimeout(() => {
      console.log(captured_i);
    }, 100);
  })(i);
}
// Correctly logs: 0, 1, 2

Here, we are manually doing what let now does for us automatically. Let's trace the execution:

  1. On each loop iteration, we define a new anonymous function.
  2. We immediately invoke this function, passing the current value of i into it.
  3. Each function invocation creates a new execution context and a new lexical environment.
  4. Inside this new environment, a new variable (captured_i) is created, holding the value passed in for that iteration.
  5. The setTimeout callback is created inside this IIFE, so it forms a closure over the IIFE's scope, capturing the unique captured_i for that iteration.

We've effectively created a new, temporary scope for each iteration to "trap" the value of i at that moment.


Solution 3: bind - The Functional Approach

A third way to solve this, leaning into a more functional style, is to use the bind method.

for (var i = 0; i < 3; i++) {
  setTimeout(function(captured_i) {
    console.log(captured_i);
  }.bind(null, i), 100);
}
// Correctly logs: 0, 1, 2

To understand this, recall what .bind() does: it creates a new function with its this context and initial arguments "bound" or pre-set.

  1. On each loop iteration, .bind(null, i) is called.
  2. It creates a new function. The null sets the this context (which we don't need here). The second argument, i, provides a value for the first parameter of the bound function.
  3. The value of i at that specific moment in the loop (0, then 1, then 2) is essentially "baked into" this newly created function.
  4. This new, pre-configured function is what gets passed to setTimeout.
  5. When the callback eventually runs, it's invoked with the value that was bound to it, correctly logging the value from its corresponding iteration.

This video gives a clear walkthrough of both the let and bind solutions.

JS Interview - Practical Closures - Question 7

This video from Steve Griffith offers a practical explanation of the let and bind solutions.

First, watch the explanation of the let solution, focusing on how block scope forces the closure to capture the variable. Then, watch the detailed walkthrough of the bind solution, paying close attention to how the current value of i is passed as a parameter to create a new function with the captured value.


Comparing the Solutions

Method Mechanism When to Use
let Per-iteration binding. The engine automatically creates a new lexical environment for each loop iteration. The default, modern, and most readable solution. Use this unless you have a specific reason not to (e.g., pre-ES6 environment).
IIFE Manual scope creation. You create a new function scope explicitly for each iteration to capture the value. In legacy codebases (pre-ES6) or if you need to perform more complex setup logic within the per-iteration scope.
bind Argument binding. You create a new function with the loop variable's value pre-filled as an argument. A more functional style, or when you also need to control the this context. It's less common for this specific problem today but demonstrates a strong command of function methods.

Conclusion

You have now dissected a classic JavaScript problem and can explain not just the solutions, but the precise memory and scope mechanics that make them work. You've connected the theory of lexical environments and the [[Environment]] slot to a practical, high-frequency interview question.

Key Takeaways:

  • The loop-closure bug with var occurs because all callbacks close over the same shared lexical environment, referencing a single variable that has changed by the time they execute.
  • let in a for loop header fixes this by creating a new, separate lexical environment for each iteration, giving each callback its own unique variable to close over.
  • The IIFE and bind solutions are manual ways of achieving the same outcome: creating a per-iteration scope or value that the callback can hold onto.

In our next lesson, we will shift from fixing bugs to building features. You'll use your deep understanding of closures to implement a memoize function from scratch—a powerful and practical pattern for caching the results of expensive function calls, and another favorite in senior-level interviews.