Module Pattern
The Module Pattern is JavaScript's most iconic encapsulation pattern. Using IIFE and closures, it creates truly private state and exposes a controlled public API — enabling encapsulation long before classes and ES Modules existed.
What is the module pattern in JavaScript?
The module pattern uses a function scope, classically an IIFE, to keep variables private and return only a public API. It was the main way to organise code before ES modules existed. Today, ES module files give you the same privacy (anything not exported is private), but the pattern still appears in older code and in closures-based factories.
const counter = (() => {
let count = 0; // private
return {
increment: () => ++count,
reset: () => { count = 0; },
};
})();
counter.increment(); // 1
counter.count; // undefinedModule Pattern Anatomy
IIFE Wrapper
(function() { ... })()Wraps all code in a function scope. Called immediately. Variables inside don't pollute global scope.
Private State
let _count = 0; const _items = [];
Variables declared inside the IIFE are truly private. No external code can access or modify them directly.
Public API
return {
increment() { ... },
getCount() { ... }
}Returned object contains only the methods/properties you choose to expose. Closes over private state.
When to Use Module Pattern
Good use cases
- •Global namespace management in vanilla JS
- •Library code that must work without a bundler
- •Plugin systems with extensible registries
- •Singleton services (config, event bus, cache)
- •Legacy codebases adding encapsulation
- •Browser userscripts / bookmarklets
Prefer ES Modules when
- •Using a modern bundler (Vite, Webpack, Rollup)
- •Need tree-shaking / dead code elimination
- •Want static analysis and IDE auto-import
- •TypeScript project (ES Modules with types)
- •Need lazy loading / dynamic import()
- •Modern Node.js project (ESM support)
Common Pitfalls
Interactive Demo
Code Editor
<button id="inc">Increment</button>
<button id="reset">Reset</button>
<p id="out"></p>Preview
The Module Pattern: summary
Key points
- IIFE means Immediately Invoked Function Expression:
(() => { … })(). - Privacy comes from closures; the returned functions still see
count. - With ES modules, simply don't export what should stay private.
Frequently asked questions
›Is the module pattern still used?
Less often, since ES modules handle encapsulation natively. You'll still see it in legacy code and when creating private state for a single object.