🟑 MediumClosures & ScopeπŸ’» Output Question

IIFE closure

πŸ’‘

Hint

IIFEs create new scope β€” the pre-let solution to capture loop variable values.

What does this output?

for (var i = 0; i < 3; i++) {
  (function(j) {
    setTimeout(() => console.log(j), 0);
  })(i);
}

Correct Output

0
1
2

Why this output?

Explanation: The IIFE creates a new function scope for each iteration, capturing the current value of i as j. This was the pre-let fix for the classic closure bug.

Key Insight: IIFEs create new scope β€” the pre-let solution to capture loop variable values.

More Closures & Scope Output Questions

🟒 EasyClassic var in loop closureβ†’πŸŸ’ Easylet in loop closure (fix)β†’πŸŸ‘ MediumClosure counterβ†’πŸ”΄ HardClosure variable lookupβ†’

Practice predicting output live β†’

66 output questions with instant feedback

πŸ’» Try Output Quiz