šŸ“• Build AI Agents using LangGraph.js is now out!

How to check if a Javascript function was called with the new operator

We can use new.target to detect if a Javascript function is called as a constructor.

For example, let's say we have the following situation:

function Cat() {}

//  normal function call
Cat()
// call as a constructor
const myCat = new Cat()

We can use the new.target Javascript meta property to differentiate between the two different function calls:

function Cat() {
    if (new.target) {
        console.log('Called as a constructor')
    }
    else {
        console.log('Called as normal function')
    }
} 

This is quite nice because we can restrict a Js function to be called only as a constructor:

function Cat() {
    if (!new.target) {
        throw new TypeError('Cat() function needs to be called as a constructor'); 
    }
}

And you can use new.target.name to retrieve the name of the constructor:

function Cat() {
    if (new.target) {
        console.log(new.target.name) // Cat
    }
} 

Something similar to what the name property of a Javascript function can do.

The overall support for new.target is great, being available in all browsers.

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


Leave a Reply

Your email address will not be published. Required fields are marked *