Back to results for “Design Patterns in JavaScript”
JavaScript › Design Patterns in JavaScript

What is the Module pattern and what problem does it solve?

Beginner

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()); // 1
Real-world example Building a small state-tracking utility without leaking its internal variable to the global scope.

Common follow-ups: How do native ES modules make the classic IIFE module pattern less necessary today?