Course contentsShow
← JavaScript
Lesson 766 of 2,72318. ClassesFree lesson

Return Values from Constructors

Understanding how explicit return statements in constructors can override the default instance.

Return Values from Constructors

What you'll learn: How explicit return statements in constructors can override the default behavior of creating an instance.

The Surprising Override

By default, when you use the new keyword with a constructor (or a class constructor method), JavaScript automatically returns the newly created instance. You don't need to write return this — it happens implicitly.

However, if you explicitly return an object from your constructor, JavaScript will return that object instead of the instance. This overrides the normal behavior.

The Rule

  • Returning an object: The returned object becomes the result of the new expression, replacing the instance.
  • Returning a primitive (string, number, boolean, etc.): JavaScript ignores it and returns the instance as usual.
  • No return statement: The instance is returned (normal behavior).

Example

class User {
  constructor(name) {
    this.name = name;
    
    // Explicitly returning a different object
    return { custom: 'I replaced the instance!' };
  }
}

const user = new User('Alice');
console.log(user.name);      // undefined
console.log(user.custom);    // "I replaced the instance!"

The instance with name: 'Alice' was created but immediately discarded because the constructor returned a different object.

When Would You Use This?

Rarely! This pattern can enforce singleton patterns or return cached instances, but it's confusing and usually better handled with factory functions or static methods. Most constructors should not have explicit return statements.

Key Takeaway: Returning an object from a constructor replaces the default instance, while returning primitives has no effect — but avoid this pattern unless you have a very specific reason.