Loop Closures Capture Bindings Not Values

var declares one binding per loop so every callback sees the final value; let makes a fresh binding per iteration, the fix an IIFE once did by hand.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
// A closure captures the binding itself, not a copy of the value.
// var declares ONE function-scoped binding for the whole loop, so by
// the time the callbacks run, every one of them sees the final value.
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log('var sees', i), 0);
}

// let creates a fresh binding per iteration; each callback captures
// the binding of its own iteration and sees that iteration's value.
for (let n = 0; n < 3; n++) {
  setTimeout(() => console.log('let sees', n), 0);
}

// The pre-let fix did the same thing by hand: an IIFE gives each
// iteration its own scope, so captured is a per-iteration binding.
for (var j = 0; j < 3; j++) {
  ((captured) => setTimeout(() => console.log('iife sees', captured), 0))(j);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

var sees 3
var sees 3
var sees 3
let sees 0
let sees 1
let sees 2
iife sees 0
iife sees 1
iife sees 2

What the code does

The core work runs in nested loops — outer for (var i = 0; i < 3; i++), inner for (let n = 0; n < 3; n++).

Points of care

  • Nothing to vet in a supply-chain review — the file pulls in no packages.

Using it in your own code

The file’s output announces each step as it happens: var sees, let sees, iife sees.

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit.