0Pricing
JavaScript Academy · Lesson

Factory Functions

Create objects with private state via closures.

What Is a Factory Function

A factory function is any function that returns a new object. Unlike a constructor, you call it normally (no new), and it can use closures for private state.

function createUser(name) {
  return {
    name,
    greet: () => "Hi, I am " + name
  };
}
const u = createUser("Ada");
console.log(u.greet()); // "Hi, I am Ada"

No new Keyword

Factories avoid the pitfalls of new and this. You simply call the function and get an object back.

function point(x, y) {
  return { x, y };
}
const p = point(3, 4);
console.log(p.x, p.y); // 3 4

All lessons in this course

  1. How Closures Capture State
  2. Private Variables with Closures
  3. The Module Pattern (IIFE)
  4. Factory Functions
← Back to JavaScript Academy