Course contentsShow
← JavaScript
Lesson 1806 of 2,72338. Object-Oriented PatternsFree lesson

Factory Functions: Return Plain Objects

Learn how factory functions return new objects without 'new', offering flexibility and closure-based encapsulation.

Factory Functions: Return Plain Objects

You'll learn how to create objects using simple functions that return plain objects—no class, no new, no fuss.

The Core Idea

A factory function is just a regular function that returns a new object every time you call it. Unlike classes (which require new), you call a factory function like any other function, and it hands you back a fresh object.

Think of it like a toy factory: you don't construct toys yourself with special tools—you just ask the factory, and it gives you a completed toy ready to use.

// Factory function - returns a plain object
function createUser(name, age) {
  return {
    name: name,
    age: age,
    greet() {
      return `Hi, I'm ${name}`;
    }
  };
}

const user1 = createUser('Alice', 30);  // No 'new' keyword!
const user2 = createUser('Bob', 25);

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

Why Factory Functions?

Factory functions offer flexibility and closure-based encapsulation. Notice how the greet method references name from the outer function scope? That's a closure—the returned object's methods can access the factory function's parameters privately. No this binding confusion, and each object gets its own isolated copy of data.

function createCounter(start) {
  let count = start;  // Private variable via closure
  
  return {
    increment() { return ++count; },
    getCount() { return count; }
  };
}

const counter = createCounter(10);
counter.increment();  // 11
console.log(counter.count);  // undefined - truly private!

Key Takeaway: Factory functions return plain objects without requiring new, offering simplicity, closure-based privacy, and freedom from this complexity.