How to get the Class Name of an Object in JavaScript

By Cronos Editorial Staff on May 02, 2022
Est. Reading: 2 minutes
Contents

Class Name of an Object in JavaScript

While JavaScript is not strictly typed like languages such as C# or Java, it does still have class support. Originally, working with classes was mostly done through “constructor” functions and methods added to the prototype of that function which allowed you to use a JavaScript class similar to how you would in object-oriented programming languages. With ES6, you are now able to define classes in a more familiar syntax even though the underlying structure still functions as it did before.

The more you use classes, the more likely you will need to access metadata about a given class. So, how do you get a class’s name in JavaScript?

  • If you need the class name of an object, use yourObject.constructor.name
  • If you just need the name of a class in a static context, use Class.name

What’s the difference? Here is an example:

				
					class Blog {
  review() {
    console.log("This blog is great!");
  }
}
const myBlog = new Blog();
console.log(myBlog.constructor.name); // 'Blog'
console.log(myBlog.name); // undefined
console.log(Blog.name); // 'Blog'
console.log(Blog.constructor.name); // undefined
				
			

As you can see above, both solutions are similar but there is an important distinction. The name property is undefined once the class is instantiated so you will need to use Blog.constructor.name if you are trying to get the class name of an object. If you only want a string representation of a class’s name, and you have the class, just use Blog.name. Something important to keep in mind is that if you decide to add a static name property or get method to your class, you will effectively replace the original name of that class:

				
					class Person {
  static name = "Human";
}
const person = new Person();
console.log(person.constructor.name); // 'Human'
console.log(Person.name); // 'Human'
class Vehicle {
  static get name() {
    return "Automobile";
  }
}
const vehicle = new Vehicle();
console.log(vehicle.constructor.name); // 'Automobile'
console.log(Vehicle.name); // 'Automobile'
				
			

Other than that, the process of getting a class’s name in JavaScript is pretty simple despite not being completely straightforward. Enjoy!

Read More: Terraform vs Cloudformation

Related Posts

Leave a Reply

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