Closure in a Loop
Fix the buggy makeMultipliers(n) function.
It should return an array of n functions where calling functions[i](x) returns i * x. The starter code has the classic var-in-loop closure bug — run it and observe that every function returns the same wrong value.
// Expected behavior
const fns = makeMultipliers(5);
fns[0](10); // 0 (0 * 10)
fns[1](10); // 10 (1 * 10)
fns[2](10); // 20 (2 * 10)
fns[3](10); // 30 (3 * 10)
fns[4](10); // 40 (4 * 10)
// What the buggy version produces
fns[0](10); // 50 ← WRONG! (i = 5 = n after loop)
fns[1](10); // 50 ← WRONG!
Why the bug exists
With var, the loop variable i is function-scoped — there's only one i shared by all closures. By the time any function actually runs, the loop has finished and i === n.
Three valid fixes
// Fix 1: let (each iteration creates a new block-scoped i)
for (let i = 0; i < n; i++) { ... }
// Fix 2: IIFE (immediately-invoked function creates a new scope)
for (var i = 0; i < n; i++) {
result.push((function(captured) {
return x => captured * x;
})(i));
}
// Fix 3: Capture with a const
for (var i = 0; i < n; i++) {
const captured = i;
result.push(x => captured * x);
}
Examples
Input: [5,0,10]
Output: 0
Input: [5,1,10]
Output: 10
Hints
The bug: `var` is function-scoped. By the time any function runs, the loop has ended and `i === n`.
Fix 1 (simplest): Replace `var` with `let`. Each loop iteration gets its own block-scoped `i`.
Fix 2 (classic): Use an IIFE to create a new scope per iteration — `(function(i) { ... })(i)`.
Closure in a Loop
Implement makeMultipliers(n) that returns an array of n functions where functions[i](x) returns i * x — fixing the classic var-in-loop closure trap.