Compile Ready
Module 13 · JavaScript Design Patterns

The Factory Pattern

Intermediate10m read14m practice24m total
Design PatternsFactory FunctionsObject CreationPolymorphism

Introduction

The Factory Pattern centralises object creation in a function. Instead of calling new directly throughout the codebase, callers ask a factory for an object that satisfies a contract.

In JavaScript, factories are especially natural because functions can return object literals, closures can provide private state, and the factory can choose different implementations at runtime.

Why This Matters

Factory questions reveal whether you can design flexible APIs rather than just write classes. Interviewers often ask for factories when they want object creation without new, conditional creation based on type, or private per-object state through closures.

Theory

Core idea

A factory is a function whose job is to create and return objects. The caller does not need to know the exact construction details. It only depends on the methods or properties the returned object promises to provide.

Factory function vs class constructor

A class constructor is invoked with new and usually creates instances that share methods through a prototype. A factory is just a normal function. It can return any object, reuse cached objects, compose behaviour from smaller functions, or return different shapes based on input.

When factories are a good fit

Use a factory when:

  • object creation has validation or defaults,
  • callers should not care which concrete implementation they receive,
  • you want closure-based private state,
  • you want to compose small behaviours instead of building an inheritance tree,
  • tests need easy dependency injection.

Trade-offs

Factories are flexible, but if every call creates many new methods, memory use can be higher than prototype methods on a class. You can reduce that cost by sharing stateless helper functions outside the factory or by returning objects that delegate to shared behaviour.

Visual Diagrams

Factory creates the right object
caller options
     |
     v
factory function
     |
     +-- validates defaults
     +-- chooses implementation
     +-- creates private state if needed
     |
     v
object with expected public contract

The caller depends on the returned contract, not on construction details.

Code Examples

A factory with private state

Each counter returned by the factory owns a separate value variable.

Loading…

Factory chooses an implementation

The caller receives an object with the same format method, regardless of which implementation the factory selected.

Loading…

Playground

Loading editor…
Console

Press Run to execute the code and see output here.

Output Prediction

Predict the output #1

javascript
1function createCounter(label) {
2 let value = 0;
3
4 return {
5 increment: function () {
6 value += 1;
7 console.log(label + ':' + value);
8 }
9 };
10}
11
12const a = createCounter('A');
13const b = createCounter('B');
14
15a.increment();
16a.increment();
17b.increment();

Coding Exercises

Implement a shape factory

Medium

Implement createShape(type, options) without using new. It should support circle with radius and rectangle with width and height. Each returned object must have area() and describe() methods. Throw an error for an unknown shape type.

Interview Questions

1When would you prefer a factory function over a class in JavaScript?

Prefer a factory when construction needs conditional logic, validation, defaulting, dependency injection, or closure-based private state. Factories are also useful when callers should depend on an interface rather than a specific class. Prefer classes when you need a clear prototype, inheritance with extends, or many instances sharing methods efficiently.

Asked at:GoogleAmazonStripe

Follow-ups

  • What is the memory trade-off of returning methods from a factory?
  • How can factories support dependency injection?
2Does the factory pattern require returning a new object every time?

No. A factory centralises creation, but it can return a new object, a cached object, a singleton, a pooled object, or different implementations based on inputs. The important idea is that callers ask the factory instead of constructing concrete objects directly.

Quiz

1. What is the main purpose of a factory function?

2. Which scenario is a strong reason to use a factory?

Summary

  • A factory is a normal function that creates and returns objects.
  • Factories avoid exposing construction details and do not require `new`.
  • They are useful for conditional creation, private state, composition, and dependency injection.
  • Classes can be more memory-efficient for many instances because prototype methods are shared.

Cheat Sheet

Shape: function createThing(options) { return { ...methods }; }

Use when: creation has branching, validation, defaults, or private closure state.

Factory vs class: factory is a normal function; class usually uses new and prototype methods.

Trade-off: flexible creation, but repeated per-instance methods can cost memory.

Interview phrase: callers depend on the returned contract, not on concrete construction.