Explore Library
Code Quiz

Shared State in a Counter Module

A module-pattern counter leaks private state across all instances because of where the closure variable lives.

Codejavascript
const Counter = (function () {
  let count = 0;

  function Counter() {}

  Counter.prototype.increment = function () {
    return ++count;
  };

  return Counter;
})();

const a = new Counter();
const b = new Counter();

console.log(a.increment()); // expected 1
console.log(a.increment()); // expected 2
console.log(b.increment()); // expected 1, but logs 3

The counter is meant to give each instance its own private count. What is the bug?