JS Built-ins
Closuresbeginner

Closures β€” Scope in loops (let)

πŸ“– Usage Example
const fns = []
for (let i = 0; i < 3; i++) {
  fns.push(() => i)
}
fns[0]()  // β†’ 0
fns[1]()  // β†’ 1
fns[2]()  // β†’ 2

Using let in a for-loop creates a new block-scoped binding per iteration, so each closure captures its own independent copy of i.

Block Scope in Loops

Understanding how let creates a new binding in each loop iteration.

Challenge: Create an array of functions using a for loop with let i. Each function should capture the value of i at the time it was created. When you call the functions, they should return the correct captured values, not the final value of i.

Example:

const fns = []
for (let i = 0; i < 3; i++) {
  fns.push(() => i)
}
fns[0]()  // 0
fns[1]()  // 1
fns[2]()  // 2
πŸ’‘ Hints (3)
  • β€’ Each iteration of a let-based loop creates a new binding
  • β€’ Closure captures the binding, not just the value
  • β€’ This is different from var which would have shared scope