Course contentsShow
← JavaScript
Lesson 741 of 2,72317. Prototypes and InheritanceFree lesson

Guarding Against Missing 'new'

Use 'new.target' inside constructors to detect and handle calls made without the 'new' keyword.

Guarding Against Missing 'new'

You'll learn how to make constructor functions safer by detecting when they're called without the new keyword.

The Problem Recap

As you learned in the previous lesson, forgetting new when calling a constructor function can cause serious bugs—this points to the global object instead of a new instance, potentially polluting global scope or causing crashes.

The new.target Solution

Inside any function, the special new.target property tells you whether the function was called with new or not:

  • When called with new: new.target equals the constructor function itself
  • When called without new: new.target is undefined

You can use this to guard your constructors:

function Car(model) {
  // Detect missing 'new' and fix it automatically
  if (!new.target) {
    return new Car(model);
  }
  
  this.model = model;
}

// Both work correctly now!
const car1 = new Car('Tesla');
const car2 = Car('Honda');  // Automatically adds 'new'

console.log(car1.model);  // 'Tesla'
console.log(car2.model);  // 'Honda'

How It Works

Think of new.target as a security guard at the entrance. The guard checks: "Did you come in through the proper new entrance?" If not, the guard redirects you properly by making the correct new call on your behalf.

Alternative: Throwing an Error

Instead of auto-correcting, you might prefer to alert developers immediately:

function Car(model) {
  if (!new.target) {
    throw new Error('Car must be called with new');
  }
  this.model = model;
}

Key Takeaway: Use new.target inside constructor functions to detect missing new and either auto-correct the call or throw a helpful error, preventing silent bugs.