🟑 MediumClosures & ScopeπŸ’» Output Question

Module pattern with revealed state

πŸ’‘

Hint

Module pattern via IIFE: count and history are truly private. Only explicitly returned properties are public. Getter syntax (get log) is valid in object literals too.

What does this output?

const counter = (() => {
  let count = 0;
  const history = [];

  return {
    inc() { history.push(++count); return count; },
    dec() { history.push(--count); return count; },
    get log() { return [...history]; },
  };
})();

counter.inc();
counter.inc();
counter.dec();
console.log(counter.inc());
console.log(counter.count);
console.log(counter.log.length);

Correct Output

2
undefined
4

Why this output?

Explanation: inc: count becomes 1 (logged), 2 (logged). dec: count becomes 1 (logged). inc: count becomes 2 (logged), returns 2. counter.count: not exposed β€” undefined. counter.log getter returns [...history] β€” 4 entries.

Key Insight: Module pattern via IIFE: count and history are truly private. Only explicitly returned properties are public. Getter syntax (get log) is valid in object literals too.

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