All topics
Patternsintermediate

Module Pattern and Revealing Module Pattern

Using closures (often via an IIFE) to create private state and expose only a deliberately chosen public API.

The module pattern is one of the oldest and most foundational design patterns in JavaScript, using closures to simulate the private/public member distinction that classes in other languages provide natively, long before ES6 modules or private class fields existed. It's still worth understanding deeply because the same closure-based privacy technique underlies countless real-world utilities and libraries.

The module pattern is like a magician's workshop with a single service window: all the actual tools, notes, and half-finished tricks (private variables/functions) stay locked inside the workshop, and the only things the public ever sees are the specific finished tricks (public methods) handed out through that one window, with zero way to reach past it into the workshop itself.

Key Concepts

1
The classic module pattern wraps an IIFE around a set of private variables and functions, returning an object literal that exposes only specific methods as the public interface — anything not explicitly returned remains completely inaccessible from outside, protected purely by closure scope rather than any special privacy syntax. This gives you encapsulation without needing classes, private fields, or any ES6-specific feature at all.
2
The 'revealing module pattern' is a refinement: instead of defining public methods directly inline in the returned object literal, you define *all* functions (public and private) as regular named functions within the module's scope, and the returned object simply 'reveals' references to the ones meant to be public, mapping public names to their corresponding private implementations at the very end. This is considered slightly more readable since all function definitions look consistent, and the public API is clearly summarized in one place at the bottom of the module, rather than scattered inline.
3
With ES6 modules and private class fields now natively available, the module pattern is used less often for brand-new code, but it remains genuinely relevant for understanding legacy codebases, for environments without module bundlers, and as a foundational concept that explains *why* JavaScript later added native modules and private fields in the first place — they solved exactly the problem this pattern worked around using nothing but closures.