What is the module pattern?
JavaScriptThe short answer
The module pattern uses closures and IIFEs (Immediately Invoked Function Expressions) to create private scope. It lets you expose only the public API while keeping internal state and helper functions hidden. Before ES6 modules existed, this was the main way to organize JavaScript code and avoid polluting the global scope.
How it works
const counter = (function () { // Private — not accessible from outside let count = 0; function log(action) { console.log(`${action}: ${count}`); } // Public API — returned object return { increment() { count += 1; log('Incremented'); }, decrement() { count -= 1; log('Decremented'); }, getCount() { return count; }, };})();counter.increment(); // "Incremented: 1"counter.increment(); // "Incremented: 2"counter.getCount(); // 2// Private members are not accessibleconsole.log(counter.count); // undefinedcounter.log; // undefinedThe IIFE creates a scope. count and log are private because they are inside the function scope. The returned object is the public API.
Revealing module pattern
A variation where you define all functions privately and then "reveal" the ones you want public:
const calculator = (function () { function add(a, b) { return a + b; } function subtract(a, b) { return a - b; } function multiply(a, b) { return a * b; } function divide(a, b) { return a / b; } // Only expose add and subtract return { add, subtract };})();calculator.add(2, 3); // 5calculator.multiply; // undefined — not exposedModule pattern vs ES6 modules
With ES6, we have native modules:
// math.js — ES6 modulelet privateCount = 0; // private to this fileexport function increment() { privateCount += 1;}export function getCount() { return privateCount;}ES6 modules achieve the same goals (encapsulation, private scope, public API) but with cleaner syntax and static analysis support. The module pattern is mostly found in older codebases now, but the concept is still important to understand.
Interview Tip
Show the IIFE example with private variables and a returned public API. Explain that this was how JavaScript achieved encapsulation before ES6 modules. If the interviewer asks about modern alternatives, mention ES6 modules and how they provide the same benefits with cleaner syntax.
Why interviewers ask this
The module pattern is foundational to understanding JavaScript scope and closures. Interviewers ask about it to see if you understand how privacy works in JavaScript and how the language evolved from IIFEs to ES6 modules. It also shows if you can work with older codebases.