Understanding the Factory Pattern in Vanilla JavaScript

Bhavesh Prajapati
The Factory Pattern is a creational design pattern that allows us to create objects without exposing the exact class of the object that’s being created. It centralizes the creation logic in a single place, making it easy to create different objects dynamically. Let’s break this down in Vanilla JavaScript :
Why Use the Factory Pattern ?
- Centralized Object Creation : Keeps object creation in one place.
- Flexibility : Easily add new object types without modifying existing code.
- Code Reusability : Simplifies object creation logic across your application.
Factory Pattern in JavaScript :
// Factory function to create car objects
function CarFactory() {
this.createCar = function (type) {
let car;
if (type === 'sedan') {
car = new Sedan();
} else if (type === 'suv') {
car = new SUV();
} else if (type === 'truck') {
car = new Truck();
}
car.type = type;
car.drive = function () {
console.log(`Driving a ${this.type}`);
};
return car;
};
}
// Car types (constructors)
function Sedan() {
this.doors = 4;
}
function SUV() {
this.doors = 4;
}
function Truck() {
this.doors = 2;
}
// Usage
const factory = new CarFactory();
const mySedan = factory.createCar('sedan');
const mySUV = factory.createCar('suv');
mySedan.drive(); // Outputs: Driving a sedan
mySUV.drive(); // Outputs: Driving a suv
Key Benefits :
- Centralized Creation : Encapsulates object creation logic in one place, so you don’t have to repeat it elsewhere.
- Flexible Object Creation : Easily create different types of objects by passing parameters to the factory method.
- Reusable Code : The factory method can be reused throughout the application, simplifying object creation.
- When to Use? : When object creation is complex or involves a lot of logic, or when object types may change in the future.
Related Articles

Breaking Down Microservices - The Future of Scalable Architecture
Microservices are revolutionizing how businesses develop and scale software. Here’s a closer look: