A factory function is a regular function that returns a new object every time it is called.

1.Basic Syntax

function createUser(name, age) {
return {
name: name,
age: age
};
}
const user1 = createUser("Zaman", 25);
const user2 = createUser("Ahmed", 30);

console.log(user1); // { name: "Zaman", age: 25 }
console.log(user2); // { name: "Ahmed", age: 30 }

2.Why Use Factory Functions?

-Simple object creation without new
-Avoids this confusion
-Can return any type of object
-Easy to add private variables using closures

3.Adding Methods in Factory Functions

function createUser(name, age) {
return {
name,
age,
greet() {
console.log(`Hello ${name}`);
}
};
}
const user = createUser("Zaman", 25);
user.greet(); // Hello Zaman

✔ Methods are created per object
✔ Can use ES6 shorthand

Factory Function Example

const u2 = createUser("Ahmed");

✔ Factory is simpler
✔ Avoids this issues

4.Using Closures for Private Variables

Factory functions can encapsulate private data:

function createCounter() {
let count = 0; // privatereturn {
increment() {
count++;
return count;
},
decrement() {
count--;
return count;
}
};
}

const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.decrement()); // 1

✔ Private count cannot be accessed outside

5.Factory Function With Inheritance

function createAdmin(name) {
const user = {
name,
role: "user"
};
return {
...user,
isAdmin: true
};
}
const admin = createAdmin("Zaman");
console.log(admin);
// { name: "Zaman", role: "user", isAdmin: true }

6.Factory Functions With ES6 Shortcuts

function createProduct(name, price) {
return {
name,
price,
getInfo() {
return `${name} costs $${price}`;
}
};
}
const product = createProduct("Laptop", 500);
console.log(product.getInfo()); // Laptop costs $500

✔ Concise and readable

Categorized in:

Javascript,