How to Get an Object’s Class Name in JavaScript

You might not know this, but JavaScript isn’t a class-based programming language as other languages are. So let’s talk about your options.

Published Categorized as JavaScript, Web & Code

Are you coming to JavaScript from Java? If the answer to this question is “yes,” then you may be wondering if there’s a JavaScript counterpart to the getClass() method in Java, which returns the runtime class of an object.

To make a long story short, there isn’t. Although Java and JavaScript are both object-oriented programming languages, Java is class-based and JavaScript is prototype-based. Which means they don’t handle inheritance the same way.

So here’s what you can do instead:

Use the typeof operator

The typeof operator lets you look up the data type of any given object or primitive value. Here’s what its syntax looks like and how you can make it work:

// Store number in a constant
const theAnswerToLife = 42;

// Check the type of the object in the constant
console.log(typeof(theAnswerToLife));

If you were to fire up your browser’s console and run this code right now, here’s what you’d see:

Depending on the type of your object or primitive value, the typeof operator will return one of the following responses:

  • undefined
  • object
  • boolean
  • number
  • bigint
  • string
  • symbol
  • function

Note that the operator will return object if your object is null. The reasons for this go back to the way that typeof null was implemented in the early days of JavaScript. If you want to know more, Axel Rauschmayer has a really good blog post on the topic.

Access the constructor.name property

The constructor.name property contains the class name of the object. In JavaScript, all objects except for null objects will have a constructor property.

Here’s how to access it:

// Store number in a constant
const theAnswerToLife = 42;

// Check the type of the object in the constant
console.log(theAnswerToLife.constructor.name);

If you were to fire up your browser’s console and run this code right now, here’s what you’d see:

This method has its fair share of limitations. For example, if the object instance was constructed by an anonymous function, it will have no data about inheritance in its constructor.name property.

By Dim Nikov

Editor of Maker's Aid. Part programmer, part marketer. Making things on the web and helping others do the same since the 2000s. Yes, I had Friendster and Myspace.

Leave a comment

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