Course contentsShow
← JavaScript
Lesson 668 of 2,72316. Object Methods and PatternsFree lesson

What Are Factory Functions?

Learn how factory functions create and return new objects without using 'new' or classes.

What Are Factory Functions?

You'll learn what factory functions are and why they're a simple, flexible way to create multiple objects without classes or constructors.

The Core Idea

A factory function is simply a regular function that creates and returns a new object. That's it!

Unlike constructors (which require the new keyword) or classes, factory functions are just plain functions. You call them like any other function, and they give you back a fresh object.

Think of it like a real factory: you send in an order (parameters), and the factory assembles and ships you a finished product (an object).

Why Use Factory Functions?

Factory functions offer a clean, straightforward pattern:

  • No new keyword required — just call the function
  • No confusion about this — you explicitly create and return objects
  • Simple to understand — it's just a function returning an object literal
  • Flexible — easy to customize what gets returned

A Simple Example

function createUser(name, age) {
  return {
    name: name,
    age: age,
    greet() {
      console.log(`Hi, I'm ${this.name}`);
    }
  };
}

const user1 = createUser('Alice', 30);
const user2 = createUser('Bob', 25);

user1.greet(); // "Hi, I'm Alice"
user2.greet(); // "Hi, I'm Bob"

Notice we just call createUser() — no new, no class. The function builds an object and hands it back to us. Each call creates a fresh, independent object.

The Pattern

Factory functions typically:

  1. Accept parameters for customization
  2. Create an object literal inside
  3. Return that object

Key Takeaway: Factory functions are regular functions that create and return new objects — a simple, no-fuss alternative to constructors and classes.