JS: new.target
new.target
(new in ECMAScript 2015)
xtodowhat 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.
- This meta-property solves a major design flow of JavaScript where there is no distinction between function and constructors, except that constructors are usually called with the
newoperator, but not always. - When not called with
newoperator, sometimes they have different behavior by design, but not always. - Yet, in functions you define, you cannot determine whether a function is called with
new.
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 {}
This is very useful for:
- Enforcing that a constructor is always used with
new - Handling inheritance in classes (it returns the actual subclass when inherited)
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
-
Prevent accidental calls without
new(make functions non-constructible): -
Auto-correct missing
new(as in the first example). -
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).