JavaScript Stale Closures
A stale closure holds an old value after the real value moved on. The closure took a snapshot when it was made, and later changes never reach it.
A snapshot keeps the old value
greetLater copies the name into a local variable. The user changes after that, so the greeting still uses the old name.
let user = "Ana";
function greetLater() {
const name = user;
return function () { console.log("Hello, " + name); };
}
const greet = greetLater();
user = "Ben";
greet();A live variable shows the new value
This closure reads the variable itself, not a copy. The timer runs after the change, so the greeting uses the new name.
let user = "Ana";
const greet = function () { console.log("Hello, " + user); };
setTimeout(greet, 50);
user = "Ben";A fresh closure picks up the new value
The first greeting is stale, so it says Ana. A new closure made after the change says Ben.
let user = "Ana";
function makeGreeter() {
const name = user;
return function () { console.log("Hello, " + name); };
}
let greet = makeGreeter();
user = "Ben";
greet();
greet = makeGreeter();
greet();Example
let score = 10;
function makeScoreLogger() {
const snap = score;
return function () { console.log("Score is " + snap); };
}
const logScore = makeScoreLogger();
score = 20;
logScore();
console.log("Live score is " + score);Key points
- Stale closure: a function that still holds an old value after the source changed
- A snapshot is a copy taken at one moment in time.
- A closure over a snapshot keeps the old value.
- A closure over the variable itself sees the new value.
- Making a fresh closure after the change picks up the new value.
In this example, makeScoreLogger copies the score into a snapshot when it runs. The score then changes to 20, but the closure still logs 10. The last line reads the live score and logs 20.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
A closure copies a value into a local variable when it is made. The value then changes. What does the closure log?