
Closures Capture Variables, Not Values
- كاتب موثّق
- ES2025
محتويات المقال
undefined. The code uses let, not var, so the usual "just switch to let" advice doesn't apply, and the developer is stuck on one question: each callback was created while toast held a real message, so why doesn't it remember that message?
The common misconception
var for let in a loop makes each callback "remember" its own index. In React, a handler from an old render keeps seeing old state, the problem, which looks a lot like a snapshot. And most variables that closures read are const values that never change, where copying and referencing look identical. The half-truth hides the mechanism: closures hold variables, and those examples work because each callback gets a different variable, not a copy.
What actually happens
A closure keeps the variable, not its value
Closures from the same scope share their variables
read below would always return 0:
function createCounter() { let count = 0; return { increment: () => ++count, read: () => count, };}const counter = createCounter();counter.increment();counter.increment();console.log(counter.read()); // 2: both closures share one countcount, only the functions that closed over it.
The queue bug, step by step
toast is declared once, before the loop, so the whole loop has exactly one toast variable. Each setTimeout call creates a closure over that same variable. The delay, on the other hand, is an argument: delay is read immediately when setTimeout is called, which is why the timing comes out right. By the time the first callback runs, the loop has finished and the last queue.shift() has stored undefined in the shared variable. All three closures read it.
const queue = ["Saved", "Synced", "Shared"];let delay = 0;let toast = queue.shift();while (toast) { setTimeout(() => console.log(toast), delay); delay += 300; toast = queue.shift();}// after 0, 300 and 600 ms: undefined, undefined, undefinedconst queue = ["Saved", "Synced", "Shared"];let delay = 0;while (queue.length > 0) { const toast = queue.shift(); // a new variable on every pass setTimeout(() => console.log(toast), delay); delay += 300;}// after 0, 300 and 600 ms: Saved, Synced, Sharedtoast, and each closure holds a different variable that nothing ever reassigns.
Why let in a for loop "works"
for statement special-cases let in its initialization. MDN spells out the steps: after each iteration's body runs, the loop creates a new scope with new let variables, initializes them with the values from the last iteration, then runs the afterthought (i++) in that new scope. So there is a copy, but the loop makes it, between iterations, into a new variable. The closure still captures a variable; it's just the one that belongs to its iteration. var is function-scoped, so it never gets this treatment, and neither does a let declared above the loop. Here is what three callbacks created in each loop log once the loop has finished:
for (var i = 0; i < 3; i++) | i for the whole function | |
let i = 0; above, then for (; i < 3; i++) | i declared outside the loop | |
for (let i = 0; i < 3; i++) | i for every iteration | |
const declared inside the loop body |
How to apply it in your project
Check where the variable is declared For each callback created in a loop, find the declaration it reads. If it's a var, or aletdeclared above the loop, every callback shares it.Declare per-iteration variables inside the loop Use for (let i …),for (const item of list)or aconstinside the body, so each pass gets its own variable.Prefer array methods for per-item callbacks list.forEach((item, i) => …)calls your function once per item, and each call gets fresh parameters, so there's no shared variable to go wrong.Snapshot before awaiting In async handlers, copy anything that might change into a local constbefore the firstawait, and use that copy afterward.
Key takeaways
A closure keeps references to variables, not copies of their values, and reads them when it runs. Closures created in the same scope share the same variables, so a change made through one is visible to all. letin aforloop works because each iteration gets a new variable; aletdeclared outside the loop is shared just likevar.Arguments are evaluated immediately and variables inside a callback are read later, which is why the delays were right and the messages weren't. When you need a snapshot, make it explicit with a constor a parameter.
التعليقات (0)