Course contentsShow
← JavaScript
Lesson 509 of 2,72313. ClosuresFree lesson

Module Pattern with Closures

Create private variables and expose public methods using closures to encapsulate implementation details.

Module Pattern with Closures

You'll learn how to use closures to create self-contained modules with private state and public interfaces.

The Core Idea

The Module Pattern uses closures to encapsulate implementation details while exposing only what's necessary. Think of it like a vending machine: users can press buttons (public methods) to get snacks, but they can't access the internal mechanics or the cash box inside (private variables). This pattern creates a clean separation between what's visible to the outside world and what's hidden.

How It Works

You create an outer function that defines private variables and inner functions. The outer function immediately returns an object containing only the functions you want to make public. Those public functions form closures over the private variables, allowing controlled access.

function createCounter() {
  // Private variable - not accessible from outside
  let count = 0;

  // Return object with public methods
  return {
    increment() {
      count++;
      return count;
    },
    decrement() {
      count--;
      return count;
    },
    getCount() {
      return count;
    }
  };
}

const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getCount());  // 2
console.log(counter.count);       // undefined - private!

The count variable is trapped in the closure created when createCounter executed. Only the three returned methods can access it. Outside code cannot directly read or modify count without going through your controlled interface.

Key Takeaway: The Module Pattern with closures lets you create private variables and expose public methods, giving you true encapsulation and control over how your data is accessed and modified.