Loop Variable Scope
You'll learn how let and var behave differently inside loops and why that matters.
The Core Difference
When you declare a loop variable with let vs var, you get fundamentally different scoping behavior:
letcreates a new binding for each iteration — each trip through the loop gets its own fresh copy of the variablevarcreates one binding for the entire loop — all iterations share the same variable
Why This Matters
Imagine you're handing out numbered tickets at a concert. With let, each person gets their own unique ticket number that never changes. With var, everyone shares one ticket that keeps getting its number overwritten.
// Using let - each iteration gets its own i
for (let i = 0; i < 3; i++) {
// Each i is independent
}
// i is not accessible here (block scoped)
// Using var - all iterations share one i
for (var i = 0; i < 3; i++) {
// All iterations reference the same i
}
// i is still accessible here! (function scoped)
Common Scoping Pitfall
The classic problem appears when creating functions inside loops:
var functions = [];
for (var i = 0; i < 3; i++) {
functions.push(function() { return i; });
}
// All functions return 3! (the final value)
var betterFunctions = [];
for (let j = 0; j < 3; j++) {
betterFunctions.push(function() { return j; });
}
// Each function captures its own j value (0, 1, 2)
With var, all functions see the same i variable after the loop finishes. With let, each function remembers its iteration's specific value.
Key Takeaway: Use let in loop declarations to avoid scoping surprises — each iteration gets its own variable binding, preventing common bugs with closures and keeping variables properly block-scoped.