🏭 JavaScript Functions Deep Dive #7: Factory Function vs Constructor Function

pushpesh kumarpushpesh kumar
3 min read

In JavaScript, there are two common patterns for creating multiple similar objects:

  1. Factory Functions

  2. Constructor Functions

Both help in object creation, but they differ in syntax, style, behavior, and flexibility.

In this article, we’ll explore:

  • βœ… What factory and constructor functions are

  • βœ… Syntax differences and best practices

  • βœ… Pros and cons of each

  • βœ… Real-world usage examples


πŸ§ͺ Why Use These Patterns?

JavaScript doesn’t have traditional classes (before ES6). Instead, we use functions to create objects β€” either:

  • Factory functions (normal functions that return objects), or

  • Constructor functions (functions used with the new keyword)


🏭 1. Factory Function β€” A Function That Returns an Object

πŸ”Ή Syntax:

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

const user1 = createUser("Alice", 25);
console.log(user1.greet()); // Hi, I'm Alice

βœ… Key Characteristics

FeatureFactory Function
Uses this?❌ Not required
Needs new keyword?❌ No
Explicit return?βœ… Yes
Easy to mix functional logic?βœ… Yes
Private variables?βœ… Easy to achieve via closure

πŸ” Private Variables Example with Closure

function createCounter() {
  let count = 0;
  return {
    increment() {
      count++;
      return count;
    },
    getCount() {
      return count;
    },
  };
}

const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.getCount());  // 1

βœ… count is truly private β€” inaccessible from outside.


πŸ‘·β€β™‚οΈ 2. Constructor Function β€” Uses this and new

πŸ”Ή Syntax:

function User(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function () {
    return `Hello, I'm ${this.name}`;
  };
}

const user2 = new User("Bob", 30);
console.log(user2.greet()); // Hello, I'm Bob

βœ… Key Characteristics

FeatureConstructor Function
Uses this?βœ… Required
Needs new keyword?βœ… Yes
return not neededβœ… Object is returned automatically
Prototype-friendly?βœ… Yes (memory efficient)

🧠 Behind the Scenes of new

When you call a constructor with new:

  1. A new object {} is created.

  2. this inside the function refers to that object.

  3. Properties are attached to this.

  4. The object is returned automatically.


πŸ’‘ When to Use What?

SituationPreferred Pattern
You need private stateβœ… Factory Function
You want to leverage prototypes for memoryβœ… Constructor
You like FP style / Reactβœ… Factory
You build utility object creatorsβœ… Factory
You’re building class-like hierarchy pre-ES6βœ… Constructor

πŸ§‘β€πŸ’» Real-World Example

πŸ”Ή Factory Example

function createProduct(name, price) {
  return {
    name,
    price,
    discount(percent) {
      return price * (1 - percent / 100);
    },
  };
}

πŸ”Ή Constructor Example

function Product(name, price) {
  this.name = name;
  this.price = price;
}

Product.prototype.discount = function (percent) {
  return this.price * (1 - percent / 100);
};

πŸ”š Summary

FeatureFactoryConstructor
Return object?Yes (explicit)Yes (implicit)
Use this?NoYes
Use new?NoYes
Easy privacy?βœ… Yes (closures)❌ No
Memory efficient with methods?❌ Noβœ… Yes (prototypes)

βœ… Final Thoughts

Both factory and constructor functions are valid ways to create objects in JavaScript. The best choice depends on:

  • Your team’s preference (OOP vs functional)

  • Performance requirements

  • Code readability and privacy needs

In modern JavaScript, factory functions are often favored due to their simplicity and composability β€” especially in React, testing utilities, and pure functions.

0
Subscribe to my newsletter

Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

pushpesh kumar
pushpesh kumar