What is the Module Pattern?

The module pattern organises code into self-contained units with private internals and a public interface; historically it was built with an IIFE returning an object, and today ES modules (import/export) provide it natively.

The classic version (pre-ES2015)

An IIFE created a private scope, kept variables and helper functions inside it, and returned an object containing only the public methods. The revealing module pattern defined everything privately and returned references to the public parts.

ES modules today

  • Every file has its own scope; nothing is global unless exported.
  • export defines the public API; everything else is private.
  • Modules run once and are cached, so module-level state is shared by all importers.
  • Static import/export enable tree shaking: bundlers drop unused exports.
  • import() loads modules lazily for code splitting.
  • Top-level await is allowed.

CommonJS

Node's older format (require / module.exports). Still common in the Node ecosystem; modern Node supports both, and ESM is the standard going forward.

Private class fields

For object-level privacy, #private fields complement module-level privacy.

Good module design

  • Export a small, intentional API.
  • Avoid side effects at import time where possible (they run once and cannot be undone, and they block tree shaking).
  • Be careful with module-level mutable state on servers: it is shared across all requests.

Code example

js
1// Classic module pattern: an IIFE with private state and a public API
2const CartModule = (function () {
3 const items = []; // private
4 const TAX = 0.2; // private
5
6 function subtotal() {
7 return items.reduce((sum, i) => sum + i.price * i.qty, 0);
8 }
9
10 // revealing module pattern: expose only what you choose
11 return {
12 add(name, price, qty = 1) {
13 items.push({ name, price, qty });
14 return this;
15 },
16 total() {
17 return +(subtotal() * (1 + TAX)).toFixed(2);
18 },
19 count: () => items.length,
20 };
21})();
22
23CartModule.add("Book", 10).add("Pen", 2, 3);
24console.log(CartModule.count(), CartModule.total()); // 2 19.2
25console.log(CartModule.items, CartModule.TAX); // undefined undefined - private
26
27// The modern equivalent is just a file:
28//
29// // cart.js
30// const items = []; // private to the module
31// const TAX = 0.2;
32// export function add(name, price, qty = 1) { items.push({ name, price, qty }); }
33// export function total() { ... }
34//
35// // app.js
36// import { add, total } from "./cart.js";
37// const { heavyChart } = await import("./chart.js"); // lazy-load another module

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app