Factory Functions in JavaScript
📌 What Are Factory Functions?
A Factory Function is a regular function that creates and returns new objects. Unlike constructor functions, factory functions don’t use the new keyword, making them simpler and more flexible for object creation. 🎉
🧩 Why Use Factory Functions?
- No need for new — avoids common mistakes.
- Easy to create multiple similar objects.
- Can encapsulate private data via closures.
- Flexible for composition and code reuse.
🛠️ Basic Example
Simple Factory Function
function createUser(name, age) {
return {
name,
age,
greet() {
console.log("Hello, " + this.name);
}
};
}
const user1 = createUser("Alice", 25);
const user2 = createUser("Bob", 30);
user1.greet(); // Hello, Alice
user2.greet(); // Hello, Bob⚠️ Note on Methods
In the example above, each object has its own copy of the greet method. This might use more memory if many objects are created.
Note
To share methods efficiently, you can combine factory functions with prototypes or use Object.create().
🧠 Factory Functions with Shared Methods
Using a Shared Methods Object
const userMethods = {
greet() {
console.log("Hi, " + this.name);
}
};
function createUser(name, age) {
const user = Object.create(userMethods);
user.name = name;
user.age = age;
return user;
}
const user1 = createUser("Alice", 25);
user1.greet(); // Hi, Alice🔒 Private Data with Closures
Factory functions can encapsulate private variables that aren’t accessible from outside:
Private Data Example
function createCounter() {
let count = 0; // private
return {
increment() {
count++;
console.log(count);
},
decrement() {
count--;
console.log(count);
}
};
}
const counter = createCounter();
counter.increment(); // 1
counter.decrement(); // 0📚 When to Use Factory Functions?
- When you want simple, flexible object creation without new
- To encapsulate private data with closures
- When preferring composition over classical inheritance
📖 Further Reading
>>“Factory functions are a powerful pattern to create objects with clear structure and privacy.” 🏭