Course contentsShow
← JavaScript
Lesson 87 of 2,7233. Variables and ScopeFree lesson

Loop Scope with var

Why var in loops shares a single binding across all iterations, causing closure issues.

Loop Scope with var

What you'll learn: Why using var in loops can cause unexpected behavior when combined with functions or asynchronous code.

The Problem with var in Loops

When you declare a loop counter with var, JavaScript creates a single binding that's shared across all iterations. Unlike let (which creates a fresh binding per iteration), var has function scope or global scope—not block scope.

This means all iterations reference the same variable. Usually this isn't noticeable, but if you create functions inside the loop (like callbacks or event handlers), they all close over that one shared variable.

The Classic Issue

for (var i = 0; i < 3; i++) {
  setTimeout(function() {
    console.log(i);
  }, 100);
}
// Logs: 3, 3, 3 (not 0, 1, 2!)

By the time the setTimeout functions run, the loop has finished and i is 3. All three functions reference the same i.

Compare with let:

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

Each iteration gets its own i with let, so each function captures a different value.

Why This Happens

var is scoped to the nearest function (or global scope), not to the loop block. There's only one i variable for the entire loop. Every function you create inside references that single variable, which keeps changing as the loop runs.

Key Takeaway: var in loops shares one variable across all iterations, causing closure issues when functions capture it—always prefer let for loop counters.