Capturing Variables, Not Values
You'll learn: Why closures see the current value of a variable, not the value it had when the closure was created.
The Core Idea
When a closure captures a variable from its outer scope, it doesn't take a snapshot of that variable's value—it captures a reference to the variable itself. This means the closure always sees whatever the variable's value is right now, even if that value changes after the closure was created.
Think of it like giving someone your home address versus a photo of your house. If you give them your address (a reference), they'll always find your current house—even if you repaint it or add a garden. But a photo (a value) stays frozen in time.
Why This Matters
function makeCounters() {
let count = 0;
function increment() {
count++;
}
function getCount() {
return count;
}
return { increment, getCount };
}
const counter = makeCounters();
console.log(counter.getCount()); // 0
counter.increment();
console.log(counter.getCount()); // 1 — sees the updated value!
Both increment and getCount captured the variable count, not its initial value of 0. When increment changes count, getCount immediately sees the new value because they both reference the same variable.
Common Pitfall: Loops
const functions = [];
for (let i = 0; i < 3; i++) {
functions.push(function() {
console.log(i);
});
}
functions[0](); // 0 (each iteration gets its own 'i' with let)
functions[2](); // 2
Each closure captures the variable from its specific loop iteration. With let, each iteration creates a new binding.
Key Takeaway: Closures capture references to variables, not snapshots of their values—they always see the variable's current state at access time.