🟑 MediumClosures & ScopeπŸ’» Output Question

Closure counter

πŸ’‘

Hint

Each function call creates a fresh closure environment β€” independent state.

What does this output?

function makeCounter() {
  let count = 0;
  return {
    inc: () => ++count,
    dec: () => --count,
    val: () => count
  };
}

const a = makeCounter();
const b = makeCounter();

a.inc(); a.inc(); b.inc();
console.log(a.val());
console.log(b.val());

Correct Output

2
1

Why this output?

Explanation: Each makeCounter() call creates an independent closure with its own count. a and b do not share state.

Key Insight: Each function call creates a fresh closure environment β€” independent state.

More Closures & Scope Output Questions

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

Practice predicting output live β†’

66 output questions with instant feedback

πŸ’» Try Output Quiz