Module Pattern
The module pattern hides private state in a closure and returns a public API object. It is how JavaScript encapsulated code before ES modules existed.
Detailed Explanation
A module, in the design-pattern sense, is not import/export. It is a function that runs once, keeps variables in its environment, and hands back methods that close over those variables. Callers see api.load() and cannot touch cache.
The historical spelling is an IIFE:
const userStore = (function () {
const cache = new Map();
return {
get(id) { /* uses cache */ },
set(id, user) { /* uses cache */ },
};
})();
The function runs immediately. cache is not a property of userStore. Only the returned methods can see it. That is encapsulation without # fields and without a file boundary.
Today you usually write the same idea as an ES module: top-level const cache is already file-private, and you export the functions. The pattern is still useful inside a file when one object needs private state and you do not want a class: a store, a widget, a connection pool wrapper.
Compared to a class, the module pattern typically creates one instance (the IIFE ran once). Method functions live on the returned object, not on a prototype, so a thousand instances would mean a thousand function objects. For a singleton service that is fine. For many instances, use a class or a factory (revealing module per call).
What it costs you: testing private state, and a shape that does not instanceof anything. You also inherit closure leaks if the returned API is long-lived and closed over more than it needs.
Reach for the module pattern (or an ES module) for a single service with hidden state. Reach for a class when you need many instances and a prototype. Reach for the revealing module pattern when you want to name internals as functions first and then pick the export list.
Code Examples
const counter = (function () {
let n = 0;
return {
inc() {
n += 1;
return n;
},
read() {
return n;
},
};
})();
console.log(counter.inc()); // => 1
console.log(counter.read()); // => 1
console.log(counter.n); // => undefinedSame idea as an ES module (separate file):
// Same idea as an ES module (separate file):
// const cache = new Map();
// export function get(id) { return cache.get(id); }Common Gotchas
One IIFE is one instance
calling the wrapper again (if you did not IIFE) creates a new cache. The trailing `()` is what makes it a singleton.
Returned methods are own properties
they do not share a prototype. Do not use this for tens of thousands of objects.
ES modules replace most IIFEs
file scope is already private. Use `export` instead of wrapping the whole file.
`this` inside the returned methods is the API object when called as `api.inc()`
extracting `const { inc } = api` loses `this` if you used it.