Typorithm · hard

Loop Closures

scope-loop-closurejavascript-coreblock-scopeclosuresloops
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Loop Closures

0%

Closures & Scope

With var, the loop has one shared i, so the deferred callbacks all log its final value 3. With let, each iteration gets a fresh block-scoped i, so the callbacks capture 0, 1, and 2 respectively.

setTimeout defers each callback, so they all run after the loop finishes. What they print depends on which i they captured.

var i is a single function-scoped binding shared across all iterations. By the time the callbacks fire, the loop has finished and i is 3, so every callback logs 3.

let i is block-scoped and re-created on each iteration, so each callback closes over a distinct i holding 0, 1, or 2 — printing 0, 1, 2 in order.

01

var gives the whole loop one shared binding.

02

let creates a fresh per-iteration binding.

03

Deferred callbacks capture the binding, not a snapshot value.

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i)); // 3, 3, 3
}
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i)); // 0, 1, 2
}

Read the implementation

Connect each part of the code to the concept before you type.

1. var loop

var i is one function-scoped binding shared by every iteration, so all callbacks see its final value.

for (var i = 0; i < 3; i++) {

2. Shared capture

Each callback closes over the same i; by the time they run the loop is done and i is 3.

setTimeout(() => console.log(i)); // 3, 3, 3

3. let loop

let i creates a fresh binding per iteration, so each callback captures a different i.

for (let i = 0; i < 3; i++) {

4. Per-iteration capture

Each callback closes over its own iteration's i, printing 0, 1, then 2.

setTimeout(() => console.log(i)); // 0, 1, 2

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Loop Closures: Lesson & Practice · Typorithm | ApplyDjinn