JS: new.target

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

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

new.target is used inside function definition body.

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

Else, new.target has a value of undefined.

function ff() {
 if (new.target) console.log("called with new.\n", "new.target value is: ", new.target);
 else console.log("called as function.\n", "new.target value is:", new.target);
}

new ff();
// called with new.
// new.target value is:  [Function: ff]

ff();
// called as function.
// new.target value is: undefined

🛑 WARNING: when used outside function body, it throws a syntax error.

🛑 WARNING: in arrow functions, new.target is not available (they inherit it from the enclosing scope).

The problem new.target solves

This meta-property solves a major design flaw of JavaScript where there is no distinction between function and constructors, except that constructors are usually called with the new operator, but not always.

When not called with new operator, sometimes they have different behavior by design, but not always. For example, for the following, new or sans new is the same:

but new new Date() and Date() have different behavior.

Yet, in functions you define, you cannot determine whether a function is called with new.

Example. in class

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

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

new Animal();
// [class Animal]

new Dog();
// [class Dog extends Animal]

JavaScript. Constructor, Class