How to get an Object's Class in JavaScript


Borislav Hadzhiev

Last updated: Oct 18, 2021


Photo from Unsplash

Get an Object's Class in JavaScript #

Use the constructor property on the object to get a reference to the object's class, e.g. obj.constructor. The constructor property returns a reference to the constructor function that created the instance object.

class Person {} const p1 = new Person(); console.log(p1.constructor); // 👉️ [class Person]

We used the Object.constructor property to get a reference of the class we used to create the object instance.

You can also verify that the constructor property points to the correct class, by using the instanceof operator.

class Person {} const p1 = new Person(); console.log(p1.constructor); // 👉️ [class Person] console.log(p1 instanceof p1.constructor); // 👉️ true

The instanceof operator checks if the value on the right hand side appears in the prototype of the value on the left hand side.

An alternative approach is to create a method on the class.

class Person { getClassName() { return this.constructor; } } const p1 = new Person(); console.log(p1.getClassName()); // 👉️ [class Person]

This is a better approach if you need to access the class of the object often. This helps us abstract some of the internals of JavaScript into a method.

Note that all objects (other than ones created using Object.create(null)) have a constructor property.

Objects that are created without a constructor function have a constructor property that points to the main Object constructor for the specific type.

console.log({}.constructor); // 👉️ [Function: Object] console.log([].constructor); // 👉️ [Function: Array]

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.