Skip to main content
TOPIC 1 OF 9 · 2 MIN READ

Factory Functions

A factory function is a function that returns a new object. It is a simple way to create multiple objects with shared properties and methods without using classes or constructors.

Key concepts

Factory Function

A function that returns a new object. Easy creation of objects without using the `new` keyword. Works well for lightweight object generation.

Step by step

Use Case:

  • Easy creation of objects without using the `new` keyword.
  • Works well for lightweight object generation.

Examples

Factory Function Example:

function createPerson(name, age) {
  return {
    name,
    age,
    greet() {
      console.log(`Hello, my name is ${this.name}`);
    }
  };
}

const person1 = createPerson('Alice', 25);
const person2 = createPerson('Bob', 30);

person1.greet(); // Hello, my name is Alice
person2.greet(); // Hello, my name is Bob

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus