QuestionsJavaScript

Module & Revealing Module pattern

Structural PatternsMediumJavaScript

Explain the Module and Revealing Module patterns. How do closures create private state, and how do ES modules relate?

What it tests

Understanding encapsulation via closures — a public API over hidden private state — and why ES modules are the modern successor.

Approach & answer

The Module pattern uses a closure to create PRIVATE state and expose only a curated PUBLIC API — JavaScript's original answer to encapsulation before the language had real modules or private class fields. The mechanism: an IIFE (immediately-invoked function expression) runs once, declares variables and functions in its local scope (invisible from outside), and RETURNS an object containing just the functions meant to be public. Those returned functions close over the private variables, so they can read/mutate them while the outside world cannot touch them directly — the closure IS the privacy boundary. The Revealing Module variant is a stylistic refinement: define everything (private and public) as locals inside the IIFE, then return an object that simply MAPS public names to those inner functions — so the return statement reads as a clean manifest of the public interface, and internal calls reference the real functions rather than `this`. Why it mattered: it prevented global-namespace pollution and simulated private members. Today ES modules (js-20) are the successor and should be your default — top-level `const`/`let` in a module file are module-scoped (private) unless `export`ed, giving the same encapsulation with static analysis, tree-shaking, and no IIFE boilerplate; and class `#private` fields (js-27) give per-instance privacy. Knowing the Module pattern still matters because you'll meet it in legacy code and it explains WHY closures are the foundation of encapsulation in JS.

Use this technique when

Encapsulating private state behind a small public API in non-module scripts, legacy codebases, or singletons; superseded by ES modules and #private fields in new code.

Complexity

O(1) — structural, no algorithmic cost.

References

js