MediumClosures & Scope💻 Output Question

IIFE captures loop variable

💡

Hint

IIFE was the pre-let solution: capture the current value as a function argument to create a new binding.

What does this output?

const fns = [];
for (var i = 0; i < 3; i++) {
  fns.push((function(j) {
    return () => j;
  })(i));
}
console.log(fns[0]());
console.log(fns[2]());

Correct Output

0
2

Why this output?

Explanation: The IIFE captures i as parameter j at call time. j is a fresh binding per IIFE invocation — not shared like var i.

Key Insight: IIFE was the pre-let solution: capture the current value as a function argument to create a new binding.

More Closures & Scope Output Questions

EasyClassic var in loop with setTimeoutEasylet in loop — each iteration gets own bindingMediumClosure mutation persists across callsEasylet block scope — inner does not leak

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz