الانتقال إلى المحتوى
FrontendJavaScript· 7 دقائق للقراءة

Closures Capture Variables, Not Values

A closure reads its outer variables when it runs, so it sees every later assignment.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • ES2025
محتويات المقال

A notification helper drains a queue of toasts and shows them 300 ms apart. The timing is perfect, but every toast logs 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

The belief: when a function is created, it takes a snapshot of the outer variables it uses. Later changes to those variables don't affect it, because it has its own copies.

It's a natural reading of the word "capture", and plenty of code seems to confirm it. Swapping 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

MDN defines a as a function bundled together with references to its surrounding state, the . Each time a scope runs, whether it's a function call, a block or a loop iteration, JavaScript creates an environment that holds that scope's variables. A function created inside keeps a reference to that environment. When the function runs, it looks up each variable there and reads whatever the variable holds at that moment.

Closures from the same scope share their variables

Two functions created in the same call see the same variables. If closures held copies, read below would always return 0:

JavaScript counter.js
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 count

MDN's closures guide builds a counter the same way, with three functions that share a single lexical environment. It's also how closures emulate private state: nothing outside can reach count, only the functions that closed over it.

The queue bug, step by step

In the toast helper, 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.

JavaScript toasts.js
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, undefined

Moving the declaration into the loop body fixes it. A block gets a new environment each time it runs, so every pass declares a brand-new toast, and each closure holds a different variable that nothing ever reassigns.

Why let in a for loop "works"

The 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:

How the loop declares the variableVariables the loop usesCallbacks log
for (var i = 0; i < 3; i++)One i for the whole function3, 3, 3
let i = 0; above, then for (; i < 3; i++)One i declared outside the loop3, 3, 3
for (let i = 0; i < 3; i++)A new i for every iteration0, 1, 2
const declared inside the loop bodyA new variable on every pass0, 1, 2

How to apply it in your project

  1. Check where the variable is declaredFor each callback created in a loop, find the declaration it reads. If it's a var, or a let declared above the loop, every callback shares it.
  2. Declare per-iteration variables inside the loopUse for (let i …), for (const item of list) or a const inside the body, so each pass gets its own variable.
  3. Prefer array methods for per-item callbackslist.forEach((item, i) => …) calls your function once per item, and each call gets fresh parameters, so there's no shared variable to go wrong.
  4. Snapshot before awaitingIn async handlers, copy anything that might change into a local const before the first await, 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.
  • let in a for loop works because each iteration gets a new variable; a let declared outside the loop is shared just like var.
  • 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 const or a parameter.

📚 المصادر

  1. Closures — MDN
  2. for: Lexical declarations in the initialization block — MDN
  3. let — MDN
  4. var — MDN

التعليقات (0)