CrackFrontendCF
Resources
Practice
CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❤️ by Tushar Khanna

CrackFrontendCF
Resources
Practice

🏭 The Factory Pattern in JavaScript – A Practical Guide

Creates objects using functions without new keyword. Use to generate multiple similar objects with private data and flexible object composition.

As JavaScript applications scale, developers often need to create multiple instances of similar objects without repeating code or tightly coupling construction logic. This is where the Factory Pattern shines. It offers a clean and flexible way to generate objects — think of it as a factory machine that churns out customized products (objects), each tailored to specific needs. -- 🔍 What Is the Factory Pattern? The Factory Pattern is a creational design pattern that uses a function (the factory) to create and return new object instances, often with shared structure but different data. Unlike constructor functions or ES6 classes, factory functions do not use and don’t rely on . They return plain objects with all the necessary properties and methods. -- 🧱 Syntax & Structure ✅ Usage: -- 🎯 Benefits of Factory Pattern Benefit Simpler, less error-prone ✅ No Can return any shape of object ✅ Composable Easily include private data using closures Feature Constructor Function Uses ✅ Yes ❌ No ✅ Yes Returns (new instance) Manual composition Built-in Easy private data ❌ Not directly -- 📦 Real-World Example: Shape Factory -- 🧠 When to Use the Factory Pattern Use it when: You need to create many similar objects with shared behavior. You want private data via closures. You don’t want to deal with or . You’re not using class-based OOP, or want a more functional approach. You need object composition rather than inheritance. -- ❗ Pitfalls to Watch Out For Memory usage: If you define methods inside the factory, each object gets its own copy (unlike methods). You can mitigate this by: Moving shared methods outside: No inheritance out of the box: While this encourages composition, it may be limiting if your design heavily relies on inheritance hierarchies. -- 🧾 Summary Explanation Creational Style Functions that return objects Key Advantages constructor functions or when OOP is overkill | -- 🔚 Conclusion The Factory Pattern in JavaScript is a clean, flexible, and powerful way to create objects. It emphasizes composition over inheritance, embraces functional programming principles, and works especially well when combined with closures to achieve true encapsulation. Whether you're building utility modules, UI components, or domain models, the Factory Pattern is a great choice for modular, testable, and maintainable code. -- <!-quiz-start --Q1: What distinguishes the Factory Pattern from constructor functions or ES6 classes? [ ] Factory functions are slower [x] Factory functions do not use keyword and don't rely on [ ] Factory functions cannot create multiple objects [ ] Factory functions require inheritance Q2: How does the Factory Pattern achieve true private data? [ ] By using the keyword [ ] By using WeakMaps [x] By using closures to encapsulate variables [ ] By using ES6 class private fields (#) Q3: What is a potential pitfall of defining methods inside a factory function? [ ] Methods cannot access private data [x] Each object gets its own copy of the methods (memory inefficiency) [ ] Methods cannot be called [ ] Methods are automatically shared via prototype <!-quiz-end --
Browser & PatternsDesign Patterns
🎭 The Facade Pattern in JavaScript – Simplifying Complex Systems
medium
🏭 The Factory Pattern in JavaScript – A Practical Guide
medium
📘 Most Important Design Patterns in JavaScript
medium
🧠 When to Use Which Design Pattern in JavaScript
medium
📦 The Module Pattern in JavaScript — A Deep Dive
medium
🧭 MVC (Model‑View‑Controller) — A Front‑End Deep Dive
medium
👀 Observer Pattern — React to Change Automatically
medium
🔒 Singleton — One Instance to Rule Them All
medium
2 of 8
LibraryBrowser & PatternsDesign Patterns4 of 14

🏭 The Factory Pattern in JavaScript – A Practical Guide

generaldesign-patternsmedium

As JavaScript applications scale, developers often need to create multiple instances of similar objects without repeating code or tightly coupling construction logic. This is where the Factory Pattern shines.

It offers a clean and flexible way to generate objects — think of it as a factory machine that churns out customized products (objects), each tailored to specific needs.


🔍 What Is the Factory Pattern?

The Factory Pattern is a creational design pattern that uses a function (the factory) to create and return new object instances, often with shared structure but different data.

Unlike constructor functions or ES6 classes, factory functions do not use new and don’t rely on this. They return plain objects with all the necessary properties and methods.


🧱 Syntax & Structure

function createUser(name, role) {
  return {
    name,
    role,
    greet() {
      console.log(`Hi, I'm ${name} and I work as a ${role}.`);
    }
  };
}

✅ Usage:

const user1 = createUser('Alice', 'Designer');
const user2 = createUser('Bob', 'Developer');

user1.greet(); // Hi, I'm Alice and I work as a Designer.
user2.greet(); // Hi, I'm Bob and I work as a Developer.

🎯 Benefits of Factory Pattern

FeatureBenefit
✅ No new keywordSimpler, less error-prone
✅ No thisNo confusion about context
✅ FlexibleCan return any shape of object
✅ ComposableCan combine factory-generated objects
✅ EncapsulationEasily include private data using closures

🔐 Adding Private Data via Closures

function createBankAccount(owner) {
  let balance = 0;

  return {
    getOwner() {
      return owner;
    },
    deposit(amount) {
      balance += amount;
    },
    getBalance() {
      return balance;
    }
  };
}

const account = createBankAccount('Tushar');
account.deposit(500);
console.log(account.getBalance()); // 500

Here, balance is truly private — you can’t access it directly from the outside.


🧬 Factory vs Constructor vs Class

FeatureFactory PatternConstructor FunctionES6 Class
Uses new❌ No✅ Yes✅ Yes
Uses this❌ No✅ Yes✅ Yes
ReturnsCustom objectthis (new instance)this
Supports InheritanceManual compositionPrototype-basedBuilt-in extends
Easy private data✅ Yes (closures)❌ Not directly✅ (with #private fields)

📦 Real-World Example: Shape Factory

function createShape(type, size) {
  if (type === 'circle') {
    return {
      type,
      radius: size,
      area() {
        return Math.PI * this.radius ** 2;
      }
    };
  } else if (type === 'square') {
    return {
      type,
      side: size,
      area() {
        return this.side ** 2;
      }
    };
  }
}

const circle = createShape('circle', 5);
const square = createShape('square', 4);

console.log(circle.area()); // 78.54
console.log(square.area()); // 16

🧠 When to Use the Factory Pattern

Use it when:

  • You need to create many similar objects with shared behavior.
  • You want private data via closures.
  • You don’t want to deal with this or new.
  • You’re not using class-based OOP, or want a more functional approach.
  • You need object composition rather than inheritance.

❗ Pitfalls to Watch Out For

  • Memory usage: If you define methods inside the factory, each object gets its own copy (unlike prototype methods). You can mitigate this by:

    • Moving shared methods outside:

      const drive = function() {
        console.log(`${this.model} is driving`);
      };
      
      function createCar(model) {
        return { model, drive };
      }
  • No inheritance out of the box: While this encourages composition, it may be limiting if your design heavily relies on inheritance hierarchies.


🧾 Summary

ConceptExplanation
Pattern TypeCreational
StyleFunctional
Core MechanismFunctions that return objects
Key AdvantagesSimplicity, flexibility, closures for privacy
Use Instead ofnew constructor functions or class when OOP is overkill

🔚 Conclusion

The Factory Pattern in JavaScript is a clean, flexible, and powerful way to create objects. It emphasizes composition over inheritance, embraces functional programming principles, and works especially well when combined with closures to achieve true encapsulation.

Whether you're building utility modules, UI components, or domain models, the Factory Pattern is a great choice for modular, testable, and maintainable code.


Quick Quiz

Test your understanding with 3 quick questions

Q1What distinguishes the Factory Pattern from constructor functions or ES6 classes?
Q2How does the Factory Pattern achieve true private data?
Q3What is a potential pitfall of defining methods inside a factory function?

Continue Reading

CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❤️ by Tushar Khanna