Revealing Module
The revealing module pattern defines functions as locals, then returns an object that reveals some of them under public names. Private helpers stay unexported.
Detailed Explanation
The module pattern can write methods inline on the returned literal. The revealing variant writes every function as a named declaration (or const fn = ...) inside the wrapper, then returns a map of which names the outside world may call.
const store = (function () {
const cache = new Map();
function get(id) {
return cache.get(id);
}
function set(id, user) {
cache.set(id, user);
}
function dump() {
return [...cache.entries()];
}
return { get, set }; // dump stays private
})();
The benefit is a single place that lists the public surface, and private helpers that can call each other by name without this. get can call dump even though dump is not revealed. In the inline-object style, private helpers are awkward (you declare them above the return, which is already this pattern).
The cost is the same as any revealing map: if a public method is extracted (const { get } = store), it still works because it does not use this. If you assign this.cache inside a revealed function, extraction breaks. Prefer closed-over variables over this in this pattern.
A factory revealing module drops the IIFE and returns a new API per call: function createStore() { ... return { get, set }; }. That is how you get many instances without a class.
ES modules are revealing by nature: you choose export function get. The pattern's remaining use is a scoped object inside a file, or teaching closures.
What it costs you: an extra name for every function (function get plus { get }). That is also documentation. Do not reveal a function that mutates internals you promised were private, and do not return cache itself.
Reach for revealing module when the public list should be obvious and helpers need to call each other. Reach for a class when you want instanceof and a prototype. Reach for ES module exports when the boundary is a file.
Code Examples
function createLogger(prefix) {
function format(message) {
return `${prefix} ${message}`;
}
function info(message) {
console.log(format(message));
}
function error(message) {
console.error(format(message));
}
return { info, error };
}
const log = createLogger("app");
log.info("ready"); // => app ready
console.log(typeof log.format); // => undefinedconst math = (function () {
function add(a, b) {
return a + b;
}
function twice(n) {
return add(n, n);
}
return { twice };
})();
console.log(math.twice(4)); // => 8Common Gotchas
Revealing a function that uses `this` reintroduces binding bugs
close over state instead of hanging it on the API object.
Returning the private map (`return { get, cache }`) undoes encapsulation
reveal operations, not the store.
File-level `export { get, set }` is the same idea without an IIFE
File-level `export { get, set }` is the same idea without an IIFE