Back to results for “Design Patterns in JavaScript”
JavaScript › Design Patterns in JavaScript

What is the Factory pattern, and how does it differ from calling a class constructor directly?

Intermediate

Answer

A factory is a function that encapsulates the logic for deciding which class/object to instantiate and how, hiding that complexity from the caller — useful when construction logic is conditional or needs to vary at runtime.
function createShape(type) {
  switch (type) {
    case 'circle': return new Circle();
    case 'square': return new Square();
    default: throw new Error('Unknown shape');
  }
}
Real-world example A UI library's createElement() function that returns different component instances based on a type string.

Common follow-ups: When would you prefer a factory function over exposing the classes directly?