šŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

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.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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