1. Function-scoped var
var has one shared, function-scoped binding for i across every iteration of the loop.
for (var i = 0; i < 3; i++) {Typorithm · medium
Step 1 of 8 · intro card
Tricky Output
A var loop shares ONE function-scoped binding, so setTimeout callbacks all read the final value (3, 3, 3). Switching to let gives each iteration its own binding, so the callbacks print 0, 1, 2.
setTimeout callbacks run after the synchronous loop has finished. With var, there is a single function-scoped i, so by the time any callback runs i has already reached 3 — every callback logs 3.
let is block-scoped and creates a brand-new binding on each iteration, so each closure captures the value i had during that iteration: 0, then 1, then 2.
Before let, the classic fix was an IIFE that copied the current value into a new scope, e.g. (function (k) { setTimeout(() => console.log(k)); })(i).
var loop + setTimeout logs 3, 3, 3.
let gives each iteration its own binding → 0, 1, 2.
Callbacks run after the loop, reading the final shared value.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0); // logs 3, 3, 3
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 0); // logs 0, 1, 2
}Connect each part of the code to the concept before you type.
var has one shared, function-scoped binding for i across every iteration of the loop.
for (var i = 0; i < 3; i++) {Each callback closes over the same i and runs after the loop ends, when i is already 3.
setTimeout(() => console.log(i), 0); // logs 3, 3, 3let creates a fresh j binding for each iteration, so each closure captures a different value.
for (let j = 0; j < 3; j++) {Because each iteration has its own j, the callbacks print 0, 1, and 2.
setTimeout(() => console.log(j), 0); // logs 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.