const fns = []
for (let i = 0; i < 3; i++) {
fns.push(() => i)
}
fns[0]() // β 0
fns[1]() // β 1
fns[2]() // β 2Using let in a for-loop creates a new block-scoped binding per iteration, so each closure captures its own independent copy of i.
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