Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 15

Module Pattern and Factory Functions with Closures

Recommended resources

In the previous lesson, we transformed our understanding of closures from a theoretical concept into a practical performance tool by implementing a memoize function. You saw how a closure creates a private, persistent "backpack" — the cache — for the function it wraps. Today, we expand on this powerful idea of encapsulation. We will use closures not just for caching, but to build two foundational JavaScript patterns: the Module Pattern and Factory Functions. These patterns are essential for creating organized, maintainable, and secure code by explicitly separating private implementation details from the public interface.

This lesson is crucial for bridging the gap between using language features and architecting systems with them. Understanding these patterns provides deep insight into how modern libraries and frameworks manage state and behavior, a key area of focus in senior-level interviews.

Why This Matters at a Senior Level

[Often asked]

A mid-level developer knows ES6 import and export. A senior engineer understands the foundational principles of encapsulation that these syntactic features are built upon. The Module and Factory patterns are the original, closure-based implementations of these principles in JavaScript. Demonstrating that you can build and explain them shows you grasp not just the "what" but the "why" of code organization. In a system design interview, explaining how you'd use a factory to create encapsulated components with private state is a massive signal of seniority. It shows you think about API boundaries, data integrity, and the long-term maintainability of a system, not just getting the immediate feature to work.


Core Concepts: Encapsulation with Closures

At its heart, encapsulation is about bundling data (state) with the methods that operate on that data, and restricting direct access to the data itself. Closures are JavaScript's natural mechanism for achieving this.

1. The Module Pattern: The Singleton Toolbox

Before ES6 introduced native modules, developers needed a way to prevent polluting the global scope and to create private state. The solution was the Module Pattern, which uses a closure, typically from an Immediately Invoked Function Expression (IIFE), to create a single, shared instance of a "module" with a private internal state and a public API.

This diagram illustrates the core idea: a `ModuleConsumer` can only interact with the public API, while the private implementation details are hidden inside the `Module`.

Let's watch a short video that sets the stage by explaining the problems this pattern was designed to solve, such as global namespace pollution and naming conflicts.

1. Module – JavaScript Design Patterns Advanced Course (1/10)

This video from Applicable Programming introduces the module pattern by first highlighting common issues in larger JavaScript applications without it.

Watch the introductory segment from the beginning to understand the motivation behind organizing code into modules, focusing on the concepts of encapsulation and namespacing.

The core implementation is surprisingly elegant. An IIFE runs once, creating a scope. Anything not explicitly returned from that function remains private to that scope, but accessible to the functions that are returned, thanks to their closure.

const ShoppingCart = (() => {
  // Private state
  const items = [];
  let totalCost = 0;

  // Private helper function
  const calculateTotal = () => {
    return items.reduce((acc, item) => acc + item.price, 0);
  };

  // Public API (returned object)
  return {
    addItem(item) {
      items.push(item);
      totalCost = calculateTotal();
      console.log(`${item.name} added.`);
    },
    
    getCartStatus() {
      console.log(`Items: ${items.length}, Total: $${totalCost}`);
    }
  };
})();

ShoppingCart.addItem({ name: 'Laptop', price: 1200 }); // "Laptop added."
ShoppingCart.getCartStatus(); // "Items: 1, Total: $1200"

console.log(ShoppingCart.items); // undefined -> Can't access private state!
// ShoppingCart.calculateTotal(); // TypeError -> Can't access private method!

In the code above, items and totalCost are completely inaccessible from the outside world. They can only be modified or read via the methods exposed on the ShoppingCart object.

The chapter "The Module Pattern" from the book You Don't Know JS Yet provides a canonical explanation of this pattern.

Chapter 8: The Module Pattern - You Don't Know JS Yet - Mintlify

This excerpt from Kyle Simpson's renowned series clearly contrasts a simple data structure with a true module that controls access to its state.

Focus on the section Modules (Stateful Access Control). Compare the Student object example with the module implementation that follows. Notice how the records array is transformed from a public property into a private variable, accessible only through the getName method on the publicAPI.

2. Factory Functions: Creating Multiple Instances

The Module Pattern is great for creating singletons, like a global configuration object or a main service. But what if you need multiple, independent instances of an object, each with its own private state? For example, multiple shopping carts for different users.

This is where Factory Functions come in. A factory function is simply a function that is not a class or constructor, and which returns a new object. When it does so, it can leverage closures to give each new object its own private, encapsulated state.

Let's watch a detailed breakdown of how factory functions work, their trade-offs, and how they achieve data privacy.

Factory Function vs. Constructor vs. Class - JavaScript Tutorial

This video from ColorCode provides an excellent comparison of object creation patterns, with a specific focus on factory functions.

First, watch the section that introduces a basic factory function and highlights a key performance issue: method duplication. The speaker explains how each object instance gets its own copy of the methods, which can be inefficient. Then, jump to the section on data privacy. This is the most crucial part for our lesson. It shows precisely how closures allow a factory to create objects with private state that cannot be accessed from the outside.

As the video explained, the simplest factory function creates private state by simply not returning it.

function createPerson(name, age) {
  // private data
  const privateAge = age; 
  const creationTime = Date.now();

  // public API
  return {
    getName() {
      return name;
    },
    greet() {
      console.log(`Hi, I'm ${name}.`);
    }
  };
}

const alice = createPerson('Alice', 30);
const bob = createPerson('Bob', 42);

alice.greet(); // "Hi, I'm Alice."
bob.greet();   // "Hi, I'm Bob."

console.log(alice.name);        // undefined
console.log(alice.privateAge);  // undefined

Each call to createPerson produces a new, independent object. alice and bob have their own closure "backpacks," each containing distinct privateAge and creationTime variables.

This pattern is extremely powerful and is a direct precursor to modern React custom hooks, which you've likely used extensively. A custom hook is essentially a factory function for stateful logic.

Replacing JavaScript Classes With The Module Design ...

This article makes a strong case for using the module/factory pattern and connects it directly to React hooks.

Read the section titled "Self-Aware" Functions. Pay close attention to the useSomeHook example. The author shows how they expose the counter value but not the raw setCounter function. Instead, they expose a custom updateCounter function that contains validation logic. This is a perfect, real-world example of using a closure to enforce data integrity.

A common criticism of naive factory functions is that each instance gets its own copy of all methods, which can be inefficient compared to the shared methods of a class's prototype.

This diagram illustrates the memory difference. The Class Implementation (left) has one set of methods on the prototype, shared by all instances (O1, O2...). The naive Closure Implementation (right) creates a new copy of the methods for each instance.

However, as the Object.create example in the video showed, and as we will explore further in our module on prototypes, it's possible to build factories that do share methods, giving you the best of both worlds: true privacy through closures and memory efficiency through prototypes.


Mental Model: The Vending Machine for Secure Briefcases

  • A Factory Function is like a high-tech vending machine that builds secure briefcases.
  • When you call the function (createPerson('Alice', 30)), you're inserting coins and selecting an item.
  • The machine (the factory) assembles a brand new briefcase (the object). Inside, it places secret documents (privateAge, creationTime) that are locked away.
  • On the outside of the briefcase, it attaches a few labeled buttons (getName, greet)—this is the public API.
  • You get your own personal briefcase. You can press the public buttons, and they can access the secret documents inside to do their job, but you can never open the briefcase to see or tamper with the documents directly.
  • Every person who uses the vending machine gets their own, completely separate briefcase.

Common Misconceptions

  1. Many developers think ES6 import/export makes the Module Pattern obsolete. Actually, while ES6 modules are the standard for file-level organization, the underlying pattern of using a function scope to create private state and a public API is more fundamental than ever. React hooks, for example, are a modern application of this exact closure-based encapsulation principle.
  2. Many developers think factory functions are just a "poor man's class". Actually, they offer advantages. They provide truly private state by default, whereas class fields in JavaScript are public (though private fields with # are now standard, they came much later). Factories also favor composition, which can lead to more flexible and decoupled architectures than classical inheritance.
  3. Many developers think "private" state in a closure is 100% secure. While it prevents direct access, if a public method returns a reference to a mutable object (like an array or object) from the private scope, the consumer of that module can then mutate that internal state. True encapsulation requires defensive copying or returning immutable data if you want to prevent this.

Senior Insight

A mid-level engineer can use class and import. A senior engineer understands that these are just two of several tools for achieving encapsulation and code organization. They can articulate the trade-offs between using a class and a factory function.

A staff engineer thinks about this at a system level. They recognize that factories excel at creating objects that follow the principle of composition over inheritance. You can easily create a createFlyingCar factory by composing the outputs of createCar() and createPlane() factories. This is often cleaner than a rigid class Car extends Vehicle hierarchy. They choose factories when they want to enforce strict API boundaries and guarantee data integrity, and they choose classes when they need the benefits of polymorphism and instanceof type checking within a more traditional OOP model. They see these not as competing patterns, but as different tools for different architectural goals.


Production War Story

A team was building a complex data grid component. The component's state (current page, sort order, filters) was managed in a large, plain JavaScript object exported from a utility file. Multiple parts of the application would import this object and change its properties directly. One day, a new feature required adding an asynchronous call whenever the filter changed. The developer added this logic in one place, but missed another place where the filter was being mutated directly.

This led to a maddeningly inconsistent bug where the grid would sometimes fail to refresh. The state object was being changed, but the necessary side-effect wasn't being triggered. After hours of debugging, the team refactored the state management to use a Module Pattern. The state object was made private within a closure. The module exposed a single function, updateGridState(newState), which performed validation, updated the private state, and reliably triggered the async refresh. Direct mutation was no longer possible, and the bug vanished instantly. The clear API boundary enforced by the module saved them from future "action at a distance" bugs.


Conclusion

In this lesson, you've moved beyond simple closures to use them as a powerful architectural tool. You now understand how to implement two foundational JavaScript patterns for creating encapsulated, maintainable code.

Key Takeaways:

  • Encapsulation: The bundling of data with the methods that operate on it, while restricting direct access. Closures are JavaScript's primary mechanism for this.
  • Module Pattern: Uses an IIFE to create a singleton with private state and a public API. Ideal for organizing code into a single, shared instance.
  • Factory Functions: Functions that return new objects. They are used to create multiple, independent instances, each with its own private state encapsulated by a closure.
  • Public vs. Private: The key is to define variables and helper functions within the closure's scope and only return an object with the methods you want to expose as the public interface.

In our next lesson, we will explore another powerful functional pattern enabled by closures: partial application. You'll learn how to create new, more specialized functions from existing ones, a technique that greatly improves code reuse and readability.