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++) {Typorithm · hard
Step 1 of 8 · intro card
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.
var gives the whole loop one shared binding.
let creates a fresh per-iteration binding.
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
}Connect each part of the code to the concept before you type.
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++) {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, 3let i creates a fresh binding per iteration, so each callback captures a different i.
for (let i = 0; i < 3; i++) {Each callback closes over its own iteration's i, printing 0, 1, then 2.
setTimeout(() => console.log(i)); // 0, 1, 2Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.