Skip to content

Module Pattern

In one line

The module pattern uses closures to create private variables and public methods, encapsulating implementation details.

In simple words

The module pattern is a design pattern that uses closures to create private state and controlled public access. Before native ES modules, it was the primary way to encapsulate code in JavaScript.

The pattern wraps code in an IIFE (Immediately Invoked Function Expression) that returns an object with only the public methods. Variables declared inside the IIFE are private — they cannot be accessed from outside, only through the returned methods.

Modern JavaScript uses ES modules (import/export) instead, which provide true file-level encapsulation. But the module pattern is still useful for creating singletons and understanding how closures enable data privacy.

Example

javascript
const counter = (function() {
  let count = 0; // private
  return {
    increment() { count++; },
    get() { return count; }
  };
})();
counter.increment();
console.log(counter.get()); // 1

The IIFE creates a private count variable. Only increment and get are exposed.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary