How to get the Class Name of an Object in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 18 20211 min read

Get the Class Name of an Object in JavaScript #

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

index.js
class Person {} const p1 = new Person(); console.log(p1.constructor.name); // ๐Ÿ‘‰๏ธ Person

We accessed the name property on the Object.constructor property.

The Object.constructor property returns a reference to the constructor function, from which the object was created.

index.js
class Person {} const p1 = new Person(); console.log(p1.constructor); // ๐Ÿ‘‰๏ธ [class Person]

An alternative approach is to create a method on the class to get the class name of the object.

index.js
class Person { getClassName() { return this.constructor.name; } } const p1 = new Person(); const className = p1.getClassName(); console.log(className); // ๐Ÿ‘‰๏ธ Person

If you need to access the Object.constructor.name property often you can create a method that hides this.

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.

index.js
console.log({}.constructor.name); // ๐Ÿ‘‰๏ธ Object console.log([].constructor.name); // ๐Ÿ‘‰๏ธ Array

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee