Hiprup

What is the module pattern in JavaScript?

The module pattern uses a function's scope (often an IIFE) to create private variables and expose only a chosen public interface.

  • Private members — variables inside the function stay hidden.

  • Public API — return an object containing only the methods you want to expose.

Note: it predates ES Modules, but the goal is the same — encapsulation and avoiding global pollution.

// IIFE Module Pattern
const Counter = (function() {
  // Private state
  let count = 0;
  const MAX = 100;

  // Private function
  function validate(n) {
    return n >= 0 && n <= MAX;
  }

  // Public API
  return {
    increment() {
      if (validate(count + 1)) count++;
      return count;
    },
    decrement() {
      if (validate(count - 1)) count--;
      return count;
    },
    getCount() { return count; },
    reset() { count = 0; }
  };
})();

Counter.increment(); // 1
Counter.increment(); // 2
Counter.getCount();  // 2
// Counter.count       // undefined (private!)
// Counter.validate()  // TypeError (private!)

// Revealing Module Pattern
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 _log(result) { console.log('Result:', result); } // Private

  return { add, subtract, multiply }; // Reveal only public
})();

The IIFE creates a closure. count and validate are private — not accessible outside. The returned object exposes only the public API (increment, decrement, getCount, reset).

The Revealing Module Pattern defines all functions privately, then returns an object mapping public names to them — cleaner when all logic is private.

Show how closures create private state. The module pattern was essential before ES modules.

Know the revealing variant (all private, selectively exposed). Modern code uses ES modules (import/export) instead, but the pattern demonstrates closure mastery.

What is the module pattern in JavaScript? | Hiprup