The Module Pattern
What you'll learn: How to use closures and IIFEs to create self-contained modules with private state and controlled public interfaces.
The Core Idea
The Module Pattern combines everything you've learned about encapsulation: it wraps code in an IIFE (Immediately Invoked Function Expression) to create private scope, then returns an object exposing only the public methods you want users to access. Everything else stays hidden inside the closure.
Think of it like a vending machine: internally it has motors, coin counters, and inventory tracking (private), but you only interact through a few buttons and a coin slot (public interface).
Basic Structure
const myModule = (function() {
// Private state
let privateCounter = 0;
const privateData = [];
// Private helper
function privateHelper() {
return privateCounter * 2;
}
// Public API
return {
increment() {
privateCounter++;
},
getCount() {
return privateCounter;
},
addItem(item) {
privateData.push(item);
return privateHelper();
}
};
})();
myModule.increment();
console.log(myModule.getCount()); // 1
console.log(myModule.privateCounter); // undefined — truly private!
Why Use It?
The Module Pattern gives you true encapsulation without classes. The IIFE runs once and disappears, but the returned object keeps the closure alive. Private variables are completely inaccessible from outside — no conventions, no workarounds.
It's especially useful for creating libraries, utilities, or any code where you want absolute control over what's exposed.
Key Takeaway: The Module Pattern uses an IIFE and closure to create private state that's impossible to access externally, exposing only a carefully controlled public API through the returned object.