Sub topic 7
Closures Capture Variables, Not Snapshots
This chapter assumes you already know what a closure is: a function plus a reference to the lexical environment where it was created. It also assumes you can trace the scope chain and know the difference between let, const, and var. Here we answer one question that causes many closure bugs: when a closure reads an outer variable, which value does it get?
The answer is the value the variable holds at the moment the closure runs. A closure keeps no copy of the value from when it was created. It holds a live link to the variable itself.
The Working Model: A Link to a Binding
A binding is the association between a variable name and a storage slot inside an environment record. When a function is created, it stores a reference to the environment record that surrounds it. Each time the function looks up a name, the engine follows that reference and reads whatever is currently in the slot.
function makeGetter() {
let value = 1;
const get = () => value;
value = 2;
return get;
}
console.log(makeGetter()()); // 2The arrow function get is created while value is 1. By the time anyone calls get, value has been reassigned to 2. The closure follows its link to the binding and finds 2.
Timers and other delayed callbacks show the same behavior:
let message = 'start';
setTimeout(() => {
console.log(message);
}, 0);
message = 'end';
// prints: endThe callback runs after the synchronous code finishes, so it reads 'end'. Nothing was "remembered" when setTimeout was called. The only thing stored was the route to message.
Closures Can Write, Too
The link works in both directions. If a closure assigns to an outer variable, it changes the shared binding, and every other function that sees that binding observes the change.
function makePair() {
let n = 0;
return {
inc: () => {
n += 1;
},
read: () => n
};
}
const p = makePair();
p.inc();
p.inc();
console.log(p.read()); // 2inc and read are two separate functions. They were created during the same call to makePair, so both point to the same environment record and the same n. When inc writes, read sees the result.
One Call, One Environment
Sharing applies only to closures created in the same call. Each call to makePair creates a fresh environment record with its own n.
function makePair() {
let n = 0;
return {
inc: () => {
n += 1;
},
read: () => n
};
}
const a = makePair();
const b = makePair();
a.inc();
a.inc();
b.inc();
console.log(a.read()); // 2
console.log(b.read()); // 1Here is the rule: closures share a variable when they share the environment record that holds it, and every function call creates a new record.
Objects: Two Layers of Reference
When the captured variable holds an object, two separate references are involved:
- The closure refers to the binding
settings. - The binding refers to an object on the heap.
Changes at either level are visible through the closure.
function track() {
let settings = { theme: 'light' };
const show = () => settings.theme;
settings.theme = 'dark'; // mutate the object
console.log(show()); // 'dark'
settings = { theme: 'contrast' }; // rebind the variable
console.log(show()); // 'contrast'
return show;
}
track();Declaring the variable with const blocks the second kind of change (rebinding) but not the first (mutation). Many developers expect const to freeze what a closure sees. It does not.
| Change made after the closure is created | Visible to the closure? | Prevented by `const`? |
|---|---|---|
| Reassign a primitive (`x = 2`) | Yes | Yes |
| Reassign an object variable (`obj = {}`) | Yes | Yes |
| Mutate a property (`obj.a = 1`) | Yes | No |
| Push to an array (`arr.push(1)`) | Yes | No |
| `Object.freeze(obj)` beforehand, then try to mutate | No change happens | Not needed |
Taking a Snapshot on Purpose
Sometimes you really do want the value as it was at a particular moment. The technique is always the same: copy the value into a new binding that nothing reassigns, and let the closure capture that binding.
Copy into a `const`
function makeLogger() {
let level = 'info';
const savedLevel = level; // snapshot taken here
const live = () => level;
const frozen = () => savedLevel;
level = 'debug';
return { live, frozen };
}
const logger = makeLogger();
console.log(logger.live()); // 'debug'
console.log(logger.frozen()); // 'info'frozen still captures a variable. That variable just never changes after it is created.
Copy through a Function Parameter
Parameters are fresh bindings for each call, so passing a value into a function creates a snapshot as well. Before let existed, this was the standard way to freeze a value.
function snapshot(value) {
return () => value;
}
let count = 10;
const atTen = snapshot(count);
count = 20;
console.log(atTen()); // 10
console.log(count); // 20Snapshots of Objects Need Copying
Copying a variable that holds an object copies the reference, not the object. To keep the closure isolated from later mutation, copy the object:
const original = { user: { name: 'Ana' }, tags: ['a'] };
const shallow = { ...original };
const deep = structuredClone(original);
const readShallow = () => shallow.user.name;
const readDeep = () => deep.user.name;
original.user.name = 'Bo';
console.log(readShallow()); // 'Bo' (nested object is still shared)
console.log(readDeep()); // 'Ana' (fully independent copy)Spread syntax copies only the top level. structuredClone copies nested data. It is available in modern browsers and Node.js 17 and later, but it cannot clone functions or DOM nodes.
Common Errors
Expecting the Creation-Time Value
This is the most common mistake. You set up a callback, change a variable later, and the callback reports the new value. If you need the old value, take an explicit snapshot as shown above.
The Stale Closure
The reverse problem also happens. A closure is linked to one particular environment record. If later code creates a new record (for example, by calling the outer function again), the old closure keeps reading the old record.
function setup(label) {
return () => console.log('label is', label);
}
let handler = setup('first');
const savedHandler = handler; // someone keeps this reference
handler = setup('second');
handler(); // label is second
savedHandler(); // label is firstsavedHandler is not broken. It is faithfully reading the binding from the first call. Stale closures show up when you store a callback somewhere (an event listener, a subscription, a cache) and later expect it to see values from a newer call. The fix is either to replace the stored callback or to have both calls read a variable that lives in a shared outer scope.
Accidental Sharing
When you create several closures in one scope that all touch the same variable, they are coupled whether you meant them to be or not. The next chapter looks at the best-known case of this: callbacks created inside a var loop all end up sharing one loop counter.
Exercises
Exercise
What does this code print, and why? function f() { let a = 1; const g = () => a * 10; a = 5; return g; } console.log(f()());
Show answer
It prints 50. The closure g reads the binding a when it is called. By then a has been reassigned to 5, so g returns 5 * 10.
Exercise
Given const x = makePair(); const y = makePair(); x.inc(); y.inc(); y.inc(); what do x.read() and y.read() return, using the makePair function from this chapter?
Show answer
x.read() returns 1 and y.read() returns 2. Each call to makePair creates its own environment record with its own n. Closures share n only with other closures created during the same call.
Exercise
Change this function so that the returned function always reports the starting score of 0, even though score changes before the function returns. function game() { let score = 0; const report = () => score; score = 100; return report; }
Show answer
Copy the value into a binding that is never reassigned, and capture that binding instead: declare const startScore = score; before the reassignment and define report as () => startScore. Passing score through a parameter also works, for example const report = ((s) => () => s)(score); written before score = 100.
Exercise
A closure captures const config = { retries: 3 }. Later code runs config.retries = 0. Does the closure see 0? How would you stop it from seeing the change?
Show answer
Yes, it sees 0. const blocks rebinding config but does not stop mutation of the object. To prevent the change, call Object.freeze(config) before other code can touch it, or have the closure capture a copy such as structuredClone(config) or { ...config } (the spread copy is enough here because the object is flat).