JS: new.target

By Xah Lee. Date: .

new.target

(new in ECMAScript 2015)

xtodo
xtodo

new.target is a special meta-property in JavaScript that tells you whether a function (or class constructor) was invoked using the new keyword.

Simple Explanation

This is very useful for:

Basic Examples

1. In a regular function:

function User(name) {
  console.log(new.target);   // ← this is the key

  if (!new.target) {
    return new User(name);   // auto-fix: call with new
  }

  this.name = name;
}

// Usage
User("Alice");     // new.target === undefined → auto creates with new
new User("Bob");   // new.target === User function

2. In a class:

class Animal {
  constructor() {
    console.log(new.target);   // Shows which constructor was actually used
  }
}

class Dog extends Animal {
  constructor() {
    super();
  }
}

new Animal();   // → Animal
new Dog();      // → Dog   (this is the powerful part for inheritance)

Common Use Cases

  1. Prevent accidental calls without new (make functions non-constructible):

    function mustBeCalledWithNew() {
      if (!new.target) {
        throw new Error("Must be called with new");
      }
    }
  2. Auto-correct missing new (as in the first example).

  3. Factory pattern or flexible constructors that behave differently based on how they're called.

Key Points

This meta-property solves a long-standing issue in JavaScript where it was hard to reliably know if new was used.