JS: new.target

By Xah Lee. Date: .

new.target

(new in ECMAScript 2015)

xtodo
xtodo

what is new.target

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

How to use new.target

When you call a function without new, new.target is undefined.

When you call a function with new, in the function body, new.target has a value that is the constructor/function that was called.

function ff() {
 if (new.target) console.log("called with new");
 else console.log("no");
}

const resultA = ff();
// prints
// no

console.log(resultA);
// undefined

const resultB = new ff();
// prints
// called with new

console.log(resultB);
// ff {}
xtodo

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):

  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.

new.target only in keyword function or class constructors

new.target is available only inside keyword function defined functions or class constructors.

Using it outside throws a syntax error.

In arrow functions, new.target is not available (they inherit it from the enclosing scope).