What is the factory pattern?

JavaScript

The short answer

The factory pattern is a way to create objects without exposing the creation logic. Instead of using new directly, you call a function that decides which object to create based on the input. This is useful when the creation logic is complex or when you want to return different types of objects based on conditions.

How it works

function createUser(type) {
if (type === 'admin') {
return {
role: 'admin',
permissions: ['read', 'write', 'delete'],
};
}
if (type === 'editor') {
return {
role: 'editor',
permissions: ['read', 'write'],
};
}
return {
role: 'viewer',
permissions: ['read'],
};
}
const admin = createUser('admin');
const viewer = createUser('viewer');

The caller does not need to know the details of how each user type is created. They just ask for what they want and get the right object back.

Real-world example — UI components

function createNotification(type, message) {
const base = { id: Date.now(), message, read: false };
switch (type) {
case 'success':
return { ...base, icon: 'check', color: 'green' };
case 'error':
return { ...base, icon: 'x', color: 'red' };
case 'warning':
return { ...base, icon: 'alert', color: 'yellow' };
default:
return { ...base, icon: 'info', color: 'blue' };
}
}

With classes

The factory pattern also works with classes when you need different class instances:

class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
}
class Truck {
constructor(make, model, payload) {
this.make = make;
this.model = model;
this.payload = payload;
}
}
function createVehicle(type, make, model, options = {}) {
if (type === 'car') return new Car(make, model);
if (type === 'truck')
return new Truck(make, model, options.payload);
throw new Error(`Unknown vehicle type: ${type}`);
}

When to use it

  • When the creation logic is complex and you want to hide it
  • When you need to create different types of objects based on input
  • When you want a single place to change how objects are created
  • When testing — factories make it easy to create test data

Interview Tip

Show a simple example where the factory function returns different objects based on a type parameter. Explain that the pattern hides creation logic and provides a clean API. If you can connect it to real usage (like creating different notification types or test fixtures), that shows practical experience.

Why interviewers ask this

The factory pattern is one of the most common design patterns in everyday JavaScript. Interviewers ask about it to see if you know how to organize object creation logic and if you understand the benefits of encapsulating that logic behind a function.