EasyClosures & Scope🐛 Debug Challenge

var in loop — all closures share one variable

Buggy Code — Can you spot the issue?

const fns = [];
for (var i = 0; i < 3; i++) {
  fns.push(() => console.log(i));
}
fns.forEach(f => f());

Fixed Code

const fns = [];
for (let i = 0; i < 3; i++) {
  fns.push(() => console.log(i));
}
fns.forEach(f => f());

Bug Explained

Bug: var is function-scoped, not block-scoped. All three closures share the same i. By the time they run, i is already 3.

Explanation: let creates a new binding per loop iteration. Each closure captures its own i — 0, 1, 2 — instead of sharing the single var i.

Key Insight: var in loops + closures = all closures see the final value. Always use let when creating closures inside loops.

More Closures & Scope Debug Challenges

MediumCounter factory shares global stateMediumShared memoize cache across all functionsEasyWallet exposes stale primitive snapshotHardDefault parameter creates new function every call

Practice spotting bugs live →

38 debug challenges with AI hints

🐛 Try Debug Lab