🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
JS MASTER CLASS /// MASTER THE ENGINE /// BUILD LOGIC /// ASYNC PATTERNS /// JS MASTER CLASS /// MASTER THE ENGINE ///

The Module Pattern | JavaScript Tutorial - In-Depth Guide

Master the Module Pattern: encapsulating private state with closures, exposing a public API via a returned object, the Revealing Module Pattern variant, and its relationship to native ES modules.

Total XP: 0|💻 javascript XP: 0

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

System Hub

Core logic.

Quick Quiz //

Can code outside the IIFE directly access a variable declared inside it that was never returned?


🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.

Before ES modules existed, the Module Pattern was how JavaScript achieved private state and a controlled public API, using nothing but closures and an immediately-invoked function expression. It still shows up throughout the ecosystem today.

1The Module Pattern | JavaScript Tutorial - In-Depth Guide Part 1

The Module Pattern wraps code in an Immediately Invoked Function Expression (IIFE), using the function's local scope to create private variables inaccessible from outside.

+
const counterModule = (function () {
  let count = 0; // private
  return {
    increment() { return ++count; }, // public
  };
})();
counterModule.increment(); // 1
counterModule.count; // undefined — truly private
localhost:3000
📦

Encapsulation via Closures

2The Module Pattern | JavaScript Tutorial - In-Depth Guide Part 2

The object returned from the IIFE defines the module's entire public API — anything not explicitly returned remains permanently inaccessible from outside.

+
const module = (function () {
  let privateData = 'secret';
  function privateHelper() { return privateData.toUpperCase(); }
  return {
    getData: () => privateHelper(), // only this is public
  };
})();
localhost:3000

Defining a Public API

3The Module Pattern | JavaScript Tutorial - In-Depth Guide Part 3

The 'Revealing Module Pattern' is a popular variant: define everything as private functions/variables first, then return an object that simply maps public names to the already-defined private implementations.

+
const revealingModule = (function () {
  let count = 0;
  function increment() { count++; }
  function getCount() { return count; }
  return { increment, getCount }; // reveal only these
})();
localhost:3000

The Revealing Module Pattern

4The Module Pattern | JavaScript Tutorial - In-Depth Guide Part 4

Native ES modules (with 'import'/'export') provide the same core benefit — encapsulation of private state with an explicit public API — as a first-class language feature, without needing an IIFE trick.

+
// counter.js — an ES module achieves the same encapsulation natively:
let count = 0; // private to this module
export function increment() { return ++count; }
localhost:3000

Relationship to ES Modules

5The Module Pattern | JavaScript Tutorial - In-Depth Guide Part 5

The classic Module Pattern is still worth recognizing because it appears throughout the existing ecosystem — older libraries, certain bundling/UMD patterns, and any codebase written before ES modules were universally supported.

+
// A common older library shape, still seen today:
var MyLibrary = (function () {
  var privateState = {};
  return {
    init: function (config) { privateState = config; },
    getConfig: function () { return privateState; },
  };
})();
localhost:3000

Still Relevant Today

6Step-by-Step Breakdown

The Module Pattern wraps code in an Immediately Invoked Function Expression (IIFE), using the function's local scope to create private variables inaccessible from outside.

Checkpoint: Can code outside the IIFE directly access a variable declared inside it that was never returned?

  • Yes, via bracket notation or similar tricks
  • No, it remains permanently private to the closure

The object returned from the IIFE defines the module's entire public API — anything not explicitly returned remains permanently inaccessible from outside.

The 'Revealing Module Pattern' is a popular variant: define everything as private functions/variables first, then return an object that simply maps public names to the already-defined private implementations.

Native ES modules (with 'import'/'export') provide the same core benefit — encapsulation of private state with an explicit public API — as a first-class language feature, without needing an IIFE trick.

Checkpoint: Do native ES modules achieve the same core encapsulation benefit as the classic Module Pattern?

  • Yes, unexported bindings are private by default
  • No, ES modules expose everything by default

The classic Module Pattern is still worth recognizing because it appears throughout the existing ecosystem — older libraries, certain bundling/UMD patterns, and any codebase written before ES modules were universally supported.

Next, we'll explore 'The Factory Pattern'.

Level Up 🚀

Advanced cheat sheets, SEO tricks, and interview prep for this topic.

Browser Support

ChromeSupported

Fully supported.

FirefoxSupported

Fully supported.

SafariSupported

Fully supported.

EdgeSupported

Fully supported.

Accessibility (A11y)

1No Direct Accessibility Implication

The Module Pattern is a code-organization technique with no direct bearing on assistive technology; its relevance is purely about maintainable, encapsulated JavaScript architecture.

SEO Implications

  • 1

    No Direct SEO Effect

    The Module Pattern is a code-architecture concept; SEO relevance is limited to general maintainability of the codebase producing rendered content.

Best Practices

Prefer Native ES Modules for New Code

They achieve the same encapsulation goals as the classic Module Pattern with cleaner syntax, native tooling support, and static analyzability that an IIFE-based approach lacks.

Recognize the Module Pattern When Reading Legacy Code

Understanding this pattern is essential for maintaining older codebases and libraries that predate widespread ES module support.

Frequent Bugs

THE BUG

Assuming a variable declared inside a Module Pattern IIFE can be accessed for debugging via the browser console by guessing its name, when it's genuinely inaccessible from outside the closure.

THE FIX

This is expected, correct behavior — true privacy is the entire point of the pattern; add a deliberate public method if you need to expose something for debugging or testing.

THE BUG

Forgetting the parentheses that immediately invoke the function expression, accidentally leaving a function declaration/expression that never actually runs.

THE FIX

Double-check the IIFE syntax: `(function () { ... })()` — both the wrapping parentheses and the trailing call parentheses are required.

Real-World Examples

A Legacy Library Namespace Using the Module Pattern

An older third-party library exposed a single global object with a controlled API, keeping its internal implementation details hidden from the pages that used it.

var AnalyticsLib = (function () {
  var events = [];
  function send(event) { events.push(event); /* ... */ }
  return {
    track: function (name, data) { send({ name, data, time: Date.now() }); },
  };
})();

Interview Prep

?Frequently Asked Questions

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Common Pitfalls & Errors

The Error //

Missing invocation parentheses on the IIFE

const mod = (function () { /* ... */ })(); // note the trailing ()

The Solution //

Ensure the wrapping function expression is both defined and immediately called.

Lesson Glossary

[01]Module Pattern

A design pattern using an IIFE and closures to create private state and a public API.

Code Preview
(function(){...})()

[02]IIFE

Immediately Invoked Function Expression — a function defined and called at the same time.

Code Preview
(function(){})()

[03]Revealing Module Pattern

A Module Pattern variant that defines everything privately, then reveals selected members via the return statement.

Code Preview
return { increment, getCount }

[04]Public API

The set of methods/properties a module intentionally exposes to its consumers.

Code Preview
returned object

[05]ES Module

JavaScript's native module system, achieving similar encapsulation via import/export.

Code Preview
export function x

Continue Learning