Sub topic 7
Closures Capture Variables, Not Snapshots
This chapter assumes you know what a closure is and how the scope chain finds a variable. When a function closes over an outer variable, it keeps a live link to that variable. It does not keep a copy of the value. Whenever the closure runs, it reads whatever the variable holds at that moment.
The Working Model
Think of a captured variable as a named slot inside a lexical environment. The closure holds a reference to the environment, so it can reach the slot. When anything writes a new value into the slot, every function that can see the slot will see the new value.
function makeGetter() {
let value = 1;
const get = () => value;
value = 2;
return get;
}
console.log(makeGetter()()); // 2get is created while value is 1, but it returns 2. The arrow function never stored 1. It stored access to the binding value, and by the time get() runs, that binding holds 2.
Shared Bindings Between Closures
Two closures created in the same call share the same environment. A change made through one of them is visible through the other.
function makePair() {
let count = 0;
return {
increment: () => { count += 1; },
read: () => count
};
}
const pair = makePair();
pair.increment();
pair.increment();
console.log(pair.read()); // 2Each call to makePair creates a fresh environment, so a second pair would start at 0 again. Sharing happens inside one call, never across calls.
Taking a Snapshot on Purpose
To freeze a value, copy it into a new binding that nothing reassigns afterward. A const declared at the point you want to capture works well, and so does a function parameter.
function makeLogger() {
let status = 'starting';
const snapshot = status; // copy the current value
const logLive = () => status;
const logSnapshot = () => snapshot;
status = 'running';
return { logLive, logSnapshot };
}
const logger = makeLogger();
console.log(logger.logLive()); // 'running'
console.log(logger.logSnapshot()); // 'starting'Both closures still capture bindings. The difference is that snapshot is never reassigned, so it behaves like a frozen value.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Expecting the value from when the function was created | The closure returns the latest value | Copy the value into a `const` or a parameter |
| Assuming two closures each get their own copy | A write through one shows up in the other | Create a separate environment per closure, for example by calling a factory again |
| Treating a captured object as frozen by `const` | Changes to the object's properties are still visible | `const` only stops reassignment. Copy or freeze the object if you need a snapshot |
The next chapter shows a common bug this behavior causes: many callbacks created in a loop all share one variable.
Exercise
What does this code log, and why? function setup() { let msg = 'hello'; const say = () => msg; msg = 'bye'; return say; } console.log(setup()());
Show answer
It logs 'bye'. The arrow function captures the binding msg, not its value at creation time. msg is reassigned to 'bye' before say runs, so say reads 'bye'.
Exercise
Change makeGetter so that the returned function always returns 1, without removing the line value = 2.
Show answer
Copy the value into a binding that is never reassigned before value changes: declare const initial = value; and then const get = () => initial;. The function now returns 1 because initial keeps the value 1.