No history yet

Introduction to Factory Functions

The Object Factory

In the real world, a factory is a place that builds things. A car factory takes raw materials and assembles them into a car. You don't need to know the details of the assembly line; you just know you get a car at the end.

A factory function in JavaScript does the same thing, but for objects. It's a function that you call to create and return an object, all configured and ready to go. You don't build the object manually; you let the factory handle it.

A factory function is any function that is not a class or constructor but returns a new object.

Let's see one in action. Here’s a simple factory for creating user objects.

function createUser(name, email) {
  return {
    name: name,
    email: email,
    greet: function() {
      console.log(`Hello, my name is ${this.name}.`);
    }
  };
}

// Create two different user objects
const user1 = createUser('Alice', 'alice@example.com');
const user2 = createUser('Bob', 'bob@example.com');

user1.greet(); // Outputs: Hello, my name is Alice.
user2.greet(); // Outputs: Hello, my name is Bob.

Notice a few things. The createUser function takes arguments, uses them to build an object literal, and then returns it. There is no new keyword and no complex constructor logic. We just call the function, and it gives us back a complete object, methods and all.

Why Use a Factory?

Factory functions offer a straightforward way to create objects, avoiding some of the complexities that can come with JavaScript's other object creation patterns, like constructor functions. With constructors, you must remember to use the new keyword. Forgetting it can lead to bugs where this doesn't behave as you expect.

Factories are just plain functions. They encapsulate the creation logic, making your code cleaner and more modular. If you need to change how objects are created, you only have to update the logic inside the factory function. Any code that uses the factory doesn't need to change.

Lesson image

This approach promotes reusability. Once you've defined a factory, you can use it anywhere in your application to create consistent objects. Let's make another factory, this time for creating products in an e-commerce app.

function createProduct(name, price, category) {
  return {
    name: name,
    price: price,
    category: category,
    display: function() {
      console.log(`${this.name} - 💲${this.price}`);
    }
  };
}

const laptop = createProduct('Laptop', 1200, 'Electronics');
const book = createProduct('The Great Gatsby', 15, 'Books');

laptop.display(); // Outputs: Laptop - 💲1200
book.display();   // Outputs: The Great Gatsby - 💲15

The createProduct factory bundles together data (name, price) and behavior (the display method). Every product object we create will have the exact same structure, which makes our code predictable and easier to manage.

Quiz Questions 1/4

What is the primary purpose of a factory function in JavaScript?

Quiz Questions 2/4

A key difference between a factory function and a constructor function is that you do not need to use the new keyword with a factory function.

That's the core idea. Factory functions are a simple yet powerful pattern for producing objects on demand.