What is the Module pattern and what problem does it solve?
Short answer
The Module pattern uses a function closure (or an ES module) to keep internal variables private and expose only a controlled public API, preventing external code from directly manipulating internal state.
Advertisement
AModel answer
The Module pattern uses a function closure (or an ES module) to keep internal variables private and expose only a controlled public API, preventing external code from directly manipulating internal state.
const counter = (function () {
let count = 0;
return {
increment: () => ++count,
get: () => count
};
})();
counter.increment();
console.log(counter.get()); // 1Real-world example
Building a small state-tracking utility without leaking its internal variable to the global scope.
Likely follow-ups
- How do native ES modules make the classic IIFE module pattern less necessary today?
Related topics