← JavaScript

Patterns & principles · 1 of 10 · 15 min read

The Module pattern

Private state from a closure, a small public surface, and why ES modules made the classic IIFE version mostly history.

  • Design patterns

The Module pattern groups related functions and state into one unit and exposes only part of it. Everything else stays unreachable from outside. In JavaScript it is not a convention bolted on with discipline — it falls out of how closures work.

The classic form

An IIFE — a function invoked immediately, so the scope exists but the function itself does not stick around:

const counter = (function () {
  let count = 0; // private: nothing outside this function can reach it

  function validate(n) {
    // also private — a helper that is not part of the public surface
    if (!Number.isInteger(n)) throw new TypeError('expected an integer');
  }

  return {
    increment() { count += 1; return count; },
    add(n) { validate(n); count += n; return count; },
    get value() { return count; },
  };
})();

console.log(counter.increment()); // 1
console.log(counter.add(5));      // 6
console.log(counter.value);       // 6
console.log(counter.count);       // undefined — there is no such property

count is not hidden by convention. There is no path to it:

console.log(Object.keys(counter));            // ["increment", "add", "value"]
console.log(JSON.stringify(counter));         // {"value":6}
console.log(Object.getOwnPropertyNames(counter)); // the same three
counter.count = 99;                            // adds an unrelated property
console.log(counter.value);                    // 6 — untouched

The revealing variant

Same idea, but everything is declared as a normal function and the return statement is a plain map of what is public. The advantage is that the public surface is one readable block at the bottom:

const cart = (function () {
  const items = [];

  function add(item) { items.push(item); return api; }
  function total() { return items.reduce((sum, i) => sum + i.price, 0); }
  function clear() { items.length = 0; }
  function logState() { console.log(items); } // deliberately not exposed

  const api = { add, total, clear }; // ← the whole public interface, in one place
  return api;
})();

console.log(cart.add({ price: 10 }).add({ price: 5 }).total()); // 15
console.log(cart.logState); // undefined

Note return api inside add: that is what makes the calls chain, and it only works because the module can reference its own public object.

Modules made most of this unnecessary

An ES module already has its own scope. Nothing is global, and only what you export is visible — so the IIFE wrapper is pure ceremony:

// counter.js
let count = 0; // private to the file, with no wrapper at all

function validate(n) {
  if (!Number.isInteger(n)) throw new TypeError('expected an integer');
}

export function increment() { count += 1; return count; }
export function add(n) { validate(n); count += n; return count; }
export function value() { return count; }
// app.js
import { increment, value } from './counter.js';
increment();
console.log(value()); // 1
// `count` and `validate` are unreachable: they were never exported
IIFE module ES module
Privacy comes from a closure the file scope
Needs a wrapper yes no
One instance yes, always yes — evaluated once per URL
Can be tree-shaken no yes
Static analysis no yes
Still worth writing rarely the default

So the honest modern answer to “do you use the Module pattern?” is: the language does it for me. Where the closure version is still the right tool is when you need more than one instance of the private state — which a file-level module cannot give you.

When you want several

A module is a singleton. A factory that returns a module is not:

function createCounter(start = 0) {
  let count = start; // one `count` per call

  return {
    increment() { count += 1; return count; },
    get value() { return count; },
  };
}

const a = createCounter();
const b = createCounter(100);
a.increment();
console.log(a.value, b.value); // 1 100 — independent

This is the Module pattern and the Factory pattern meeting: a factory whose product keeps private state in a closure. It is the most common shape of real JavaScript code that avoids classes.

Private fields do the same job differently

ES2022 added true private class fields, which cover the same need with a different trade-off:

class Counter {
  #count = 0;                       // private at the language level

  increment() { this.#count += 1; return this.#count; }
  get value() { return this.#count; }
}

const c = new Counter();
c.increment();
console.log(c.value);        // 1
console.log(Object.keys(c)); // [] — invisible
// c.#count;                 // SyntaxError, at parse time
Closure #private field
Privacy real — no reference exists real — enforced by syntax
Methods one copy per instance shared on the prototype
Memory with many instances higher lower
Works without new yes no
Inheritance awkward natural
Debugger visibility hidden in a scope shown as a private field

The per-instance cost is the real difference. Ten thousand closure-based objects hold ten thousand copies of each method; ten thousand class instances share one. For a handful of objects it does not matter, and the closure version reads better.

What it buys you

// Without the pattern — everything is reachable, so everything is a dependency:
const config = { retries: 3, _attempts: 0, _lastError: null };
config._attempts = 999; // any code anywhere can do this

// With it — the surface is the contract:
const retrier = (function () {
  let attempts = 0;
  let lastError = null;
  const MAX = 3;

  return {
    run(fn) {
      attempts = 0;
      while (attempts < MAX) {
        attempts += 1;
        try {
          return fn();
        } catch (error) {
          lastError = error;
        }
      }
      throw lastError;
    },
    get attemptsUsed() { return attempts; }, // read-only by construction
  };
})();

The point is not secrecy. It is that the things you did not expose cannot become somebody else’s dependency, so you stay free to change them.

Common mistakes

Returning the private state itself

Mistake. return { items } where items is the private array. Why it fails. You handed out the reference. The caller can push, splice and length = 0 it, and the encapsulation was theatre. What to do instead. Return a copy, or expose only the operations you intend.

const store = (function () {
  const items = ['a'];
  return {
    leaky: () => items,          // callers can mutate the real array
    safe: () => [...items],      // a copy
    count: () => items.length,   // better still: do not hand the array out
  };
})();

store.leaky().push('b');
console.log(store.count()); // 2 — the private array changed
store.safe().push('c');
console.log(store.count()); // 2 — unaffected

Writing an IIFE inside an ES module

Mistake. Wrapping a module file in (function () { … })(). Why it fails. The file already has its own scope, so the wrapper adds a layer of indentation and nothing else — and it blocks tree shaking. What to do instead. Just declare and export.

Using a module for per-user or per-request state

Mistake. Keeping a currentUser in module scope on a server. Why it fails. A module is evaluated once per process. On a server that single value is shared by every concurrent request, which is a data-leak bug, not a caching one. What to do instead. A factory per request, or pass the state in explicitly.

Check yourself

One question from the bank on what you just read. Answering here does not affect your quiz history.

What does the Module pattern achieve?

Practise Design patterns →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.