πŸ”΄ HardClosures & ScopeπŸ’» Output Question

Shared closure mutation

πŸ’‘

Hint

All three functions share the same i variable β€” and i is 4 after the loop ends.

What does this output?

function makeAdders() {
  const adders = [];
  for (var i = 1; i <= 3; i++) {
    adders.push(function(x) { return x + i; });
  }
  return adders;
}

const [add1, add2, add3] = makeAdders();
console.log(add1(10));
console.log(add2(10));
console.log(add3(10));

Correct Output

14
14
14

Why this output?

Explanation: All functions close over the same var i. After the loop, i = 4 (incremented past condition). So all return 10 + 4 = 14.

Key Insight: All three functions share the same i variable β€” and i is 4 after the loop ends.

More Closures & Scope Output Questions

🟒 EasyClassic var in loop closureβ†’πŸŸ’ Easylet in loop closure (fix)β†’πŸŸ‘ MediumClosure counterβ†’πŸŸ‘ MediumIIFE closureβ†’

Practice predicting output live β†’

66 output questions with instant feedback

πŸ’» Try Output Quiz