Revealing Module Pattern
A refinement of the Module Pattern where all logic is defined privately and a single, clean return statement reveals exactly what is public. Your API surface becomes immediately visible, self-documenting, and consistent.
What is the revealing module pattern?
The revealing module pattern is a variation of the module pattern where all functions are defined privately inside the closure, and the returned object simply maps public names to them: return { add, remove }. It makes the public API easy to see at a glance and lets private functions call each other by name.
const cart = (() => {
const items = [];
function add(item) { items.push(item); }
function total() { return items.reduce((s, i) => s + i.price, 0); }
return { add, total }; // "reveal" the public API
})();Module Pattern vs Revealing Module
| Feature | Module Pattern | Revealing Module Pattern |
|---|---|---|
| Where functions defined | Inline in return object | All private, revealed by name in return |
| API surface visibility | Scattered throughout return | Single clean return statement |
| Can rename public API | Awkward | Clean: return { pub: privateFunc } |
| Consistency | Mixed style | Uniform — everything private first |
| Override public methods | Possible (risk) | Possible but doesn't affect private calls |
| Debugging ease | Moderate | High — all logic in named functions |
Real-World Use Cases
Event Bus
on/off/emit/once — event-driven communication between modules
Config Module
Environment-aware settings with private defaults and public getter
Shopping Cart
Items array, discount, totals — all private, clean add/remove API
Logger
Private log levels/formatters, public log/warn/error/group methods
State Container
Private state, public get/set/subscribe — observable data store
Router
Private routes registry, public navigate/on/back/getPath methods
Common Pitfalls
Interactive Demo
Code Editor
<button id="add">Add $10 item</button>
<button id="clear">Clear</button>
<p id="out"></p>Preview
Revealing Module Pattern: summary
Key points
- The public API is listed in one place at the bottom.
- Overriding a revealed method from outside doesn't change internal calls, which can surprise you.
- ES module exports serve the same purpose in modern code.
Frequently asked questions
›What is the difference from the module pattern?
In the basic module pattern, methods are written directly inside the returned object. In the revealing variant, everything is defined privately first, and the return statement only exposes references.