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

Loop Scope with let

How let creates a new binding for each iteration in for loops, avoiding common bugs.

Loop Scope with let

You'll learn: How let creates a fresh, independent variable binding for each loop iteration, preventing confusing bugs that plague var.

The Problem with var in Loops

When you use var in a loop, there's only one variable shared across all iterations. This causes issues when you create functions inside loops that try to "remember" the loop variable's value — they all end up sharing the same variable.

Think of it like having one whiteboard (var) that gets erased and rewritten vs. giving each iteration its own sticky note (let).

How let Fixes This

With let, the JavaScript engine creates a brand new binding for each iteration. Each trip through the loop gets its own separate variable, even though they all have the same name.

for (let i = 0; i < 3; i++) {
  // Each iteration has its own 'i'
  console.log(i); // 0, then 1, then 2
}

This becomes critical when creating functions inside loops:

const functions = [];

for (let i = 0; i < 3; i++) {
  functions.push(function() {
    console.log(i); // Each function captures its OWN 'i'
  });
}

functions[0](); // 0
functions[1](); // 1
functions[2](); // 2

Each function "remembers" the value of i from its specific iteration because each iteration had its own i variable.

With var, all three functions would print 3 (the final value) because they'd all share the same variable.

Why This Matters

This per-iteration binding matches your intuition: you expect loop variables to be independent between iterations, not shared.

Key Takeaway: let in loops creates a fresh variable binding for each iteration, so functions created inside loops correctly capture that iteration's value — var doesn't, causing all functions to share one variable.