The Revealing Module Pattern
What you'll learn: How to write cleaner, more maintainable modules by defining functions privately first, then explicitly choosing which ones to expose publicly.
The Problem with the Module Pattern
In the standard Module Pattern (lesson 1841), you sometimes mix private and public declarations directly in your code. This can make it harder to quickly identify what's exposed and what's hidden.
How the Revealing Module Pattern Works
The Revealing Module Pattern flips the script: you define all your functions and variables privately within the module, then at the very end you return an object that "reveals" only the parts you want to make public.
Think of it like working in a lab where everything happens behind closed doors, then you open a single window to display only the finished products you want people to see.
const calculator = (function() {
// Everything is private by default
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function logOperation(result) {
console.log('Result:', result);
}
// Reveal only what you want public
return {
add,
subtract
// logOperation stays private
};
})();
calculator.add(5, 3); // 8
calculator.logOperation(); // undefined (not exposed)
The Benefit: Clarity
By scanning the return statement, you instantly know the public API. Everything else is guaranteed private. No guessing, no mixing concerns.
Key Takeaway: The Revealing Module Pattern defines all functions privately using closures, then selectively exposes them via a single return object—making your module's public interface crystal clear at a glance.