Introduction
The Factory Function works like a model or blueprint to make similar objects or items. For example, if we want to create multiple car objects instead of individual car objects, we can use the factory function to create objects easily and remove duplicity.
What is a Factory Function?
A factory function is a function that creates and returns a new object each time it is called.
Let's take one example where we first create one object and then create two objects with the same structure without a factory function. So we can understand how much duplicate code we write for the same work.
Example1.js
let car1 = {
make: 'Kia',
model: 'Seltos',
year: 2024,
getCarInfo() {
return `${this.make} ${this.model} (${this.year})`;
},
};
console.log(car1.getCarInfo());
Output

The above code creates the car1 object with the properties make, model, and year and one method getCarInfo that returns the car details. Now if we want to create another car object, we write the duplicate code as follows:.
Example2.js
let car1 = {
make: 'Kia',
model: 'Seltos',
year: 2024,
getCarInfo() {
return `${this.make} ${this.model} (${this.year})`;
},
};
console.log(car1.getCarInfo());
let car2 = {
make: 'Tata',
model: 'Punch',
year: 2023,
getCarInfo() {
return `${this.make} ${this.model} (${this.year})`;
},
};
console.log(car2.getCarInfo());
Output

In the above code, you see we write duplicate code for the same work. Duplicating code is inefficient and irreverent, especially when dealing with many similar objects. Instead, you can use a factory function to streamline object creation.
Creating Objects with Factory Functions
For the same example above, we can generate many car objects without repeating the code.
Example3.js
function createCar(make, model, year) {
return {
make: make,
model: model,
year: year,
getCarInfo() {
return `${make} ${model} (${year})`;
},
};
}
let car1 = createCar('Kia', 'Seltos', 2024);
let car2 = createCar('Tata', 'Punch', 2023);
let car3 = createCar('Maruti Suzuki', 'Ertiga', 2024);
let car4 = createCar('Honda', 'WR', 2020);
console.log(car1.getCarInfo());
console.log(car2.getCarInfo());
console.log(car3.getCarInfo());
console.log(car4.getCarInfo()); 



Join the conversation! Your thoughts help the community grow.