A factory function is a normal function that returns a new object every time it is called.
You “call the function” → it “manufactures” (creates) and returns an object.
This is why it’s called a factory.
✔ Example:
function createUser(name, age) {
return {
name,
age,
greet() {
console.log(`Hello, I am ${name}`);
}
};
}
const user1 = createUser("Teekam", 25);
const user2 = createUser("Aman", 30);
user1.greet();
user2.greet();
Each call to createUser() returns a new object.
✅ Why Do We Need Factory Functions?
Factory functions solve several problems:
1️⃣ Create multiple similar objects easily
Without repeating object structure every time.
2️⃣ Encapsulation (Private variables using closures)
You can hide data inside a factory function.
function createCounter() {
let count = 0; // private variable
return {
increment() {
count++;
console.log(count);
}
};
}
const counter = createCounter();
counter.increment(); // 1
Count is private, not accessible directly.
3️⃣ Avoid using new keyword
Factory functions do not require new, reducing errors.
4️⃣ Better for functional programming
They are simpler, composable, and flexible.
🆚 Normal Function vs Factory Function
✔ Normal Function
- Used for calculations, logic, or reusable code
- Does not return an object (usually)
- No object creation pattern
Example:
function add(a, b) {
return a + b;
}
✔ Factory Function
- Always returns a new object
- Used to create multiple similar objects
- Helps in object creation without classes or constructors
Example:
function createUser(name) {
return { name };
}
🆚 Factory Function vs Constructor Function
Different but often confused.
| Feature | Factory Function | Constructor Function |
|---|---|---|
| Call | Regular call createUser() |
Must use new User() |
| Returns | Explicit object | Implicit this |
| Private data | ✔ Yes (via closure) | ❌ Harder |
| Risk of errors | ✔ Fewer | ❌ Forgetting new breaks it |
| Flexibility | More functional | OOP style |
🧠 In Short:
Factory Functions are functions that return objects.
They help create multiple similar objects, support private data, avoidnew, and give more flexibility than constructors.