The Module pattern uses a closure (classically an IIFE) to create private state and functions, and returns a public API object that can access them. Code outside can only use what's returned, so internals can't be tampered with or collide with globals. It was the main encapsulation tool before ES2015; today ES modules (file-level scope with explicit export) and private class fields (#x) cover the same need natively, but the closure idea still powers hooks, factories and many libraries.
const counter = (function () {
let count = 0; // private
function log(msg) { console.debug(`[counter] ${msg}`); } // private
return { // public API
increment() { count += 1; log(`now ${count}`); return count; },
reset() { count = 0; },
get value() { return count; },
};
})();
counter.increment(); // 1
counter.value; // 1
counter.count; // undefined: not reachable from outside
The IIFE runs once, its local variables stay alive in the closure, and only the returned object is exposed.
Define everything privately, then "reveal" chosen members:
const auth = (() => {
let token = null;
const login = async (creds) => { token = await requestToken(creds); };
const logout = () => { token = null; };
const isLoggedIn = () => token !== null;
return { login, logout, isLoggedIn }; // token stays private
})();
It makes the public API visible at a glance at the bottom of the module. A caveat: if a private function calls another private function, patching the public reference won't affect internal calls.
ES modules: the file is the closure.
// counter.js
let count = 0; // private to the module
export function increment() { return ++count; }
export function getValue() { return count; }
Private class fields: per-instance encapsulation enforced by the language.
class Counter {
#count = 0;
increment() { return ++this.#count; }
get value() { return this.#count; }
}
new Counter().#count; // SyntaxError outside the class
Factory + closure for many independent instances:
function createCounter() {
let count = 0;
return { increment: () => ++count, get value() { return count; } };
}
export list documents the contract.(function ($) { … })(jQuery)). ES modules fix this with import.#private fields as today's native tools.Spotted a mistake or a rights concern? Report an issue