πŸ”΄ HardClosures & ScopeπŸ’» Output Question

Module pattern with closure

πŸ’‘

Hint

IIFE + closure = module pattern for private state. The gold standard before ES modules.

What does this output?

const counter = (() => {
  let _count = 0;
  return {
    increment() { return ++_count; },
    reset() { _count = 0; },
    get value() { return _count; }
  };
})();

counter.increment();
counter.increment();
console.log(counter.value);
console.log(counter._count);
counter.reset();
console.log(counter.value);

Correct Output

2
undefined
0

Why this output?

Explanation: _count is private inside the IIFE closure. The returned object can access it via closure, but external code cannot. counter._count is undefined.

Key Insight: IIFE + closure = module pattern for private state. The gold standard before ES modules.

More Closures & Scope Output Questions

🟒 EasyClassic var in loop closureβ†’πŸŸ’ Easylet in loop closure (fix)β†’πŸŸ‘ MediumClosure counterβ†’πŸŸ‘ MediumIIFE closureβ†’

Practice predicting output live β†’

66 output questions with instant feedback

πŸ’» Try Output Quiz