MediumClosures & Scope💻 Output Question

Independent counter factory instances

💡

Hint

Each factory call creates a new lexical environment. This is the module pattern for private state.

What does this output?

function makeCounter() {
  let count = 0;
  return {
    inc() { count++; },
    get() { return count; },
  };
}
const a = makeCounter();
const b = makeCounter();
a.inc(); a.inc();
b.inc();
console.log(a.get());
console.log(b.get());

Correct Output

2
1

Why this output?

Explanation: Each makeCounter() call creates a fresh closure scope with its own count. a and b are completely independent.

Key Insight: Each factory call creates a new lexical environment. This is the module pattern for private state.

More Closures & Scope Output Questions

EasyClassic var in loop with setTimeoutEasylet in loop — each iteration gets own bindingMediumIIFE captures loop variableMediumClosure mutation persists across calls

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz