JavaScript › Design Patterns in JavaScript
What is the Module pattern and what problem does it solve?
BeginnerAnswer
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.