Categories
JavaScript Answers

How to Check if a JavaScript Function is a Constructor?

Spread the love

Sometimes, we want to check if a JavaScript function is a constructor

In this article, we’ll look at how to check if a JavaScript function is a constructor.

Check if a JavaScript Function is a Constructor

To check if a JavaScript function is a constructor, we can check if we can use the new operator with it.

To do this, we write:

const handler = {
  construct() {
    return handler
  }
}

const isConstructor = x => {
  try {
    return !!(new(new Proxy(x, handler))())
  } catch (e) {
    return false
  }
}

console.log(isConstructor(() => {}))
console.log(isConstructor(class {}))

We create a proxy in the isConstructor function that takes any variable x .

Then we use the new operator on the proxy version of x , which we create with:

(new Proxy(x, handler))()

If that works, then we know the x is a constructor since we create a new instance of x .

Otherwise, an error is throw and false is returned.

Therefore, the first console log logs false and the 2nd one logs true .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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