How can you get the class name of a JavaScript object?

I’ve created a JavaScript object, and I’m looking for a way to determine its class, similar to Java’s .getClass() method. What’s the best approach in javascript get class name?

I’ve been working with JavaScript for a while now, and honestly, the most straightforward way I’ve used for javascript get class name is through the constructor’s name property. It’s simple and works just like you’d expect if you come from a Java background.

class Dog {}
const pet = new Dog();
console.log(pet.constructor.name); // "Dog"

This method is super clean when you’re directly dealing with classes you define yourself. If you’re casually exploring javascript get class name, this approach feels natural and gets the job done without any extra fuss.

Yeah, totally agree with @tim-khorev! In my experience though—especially when working with built-in objects like Dates or Regex—there’s a slightly deeper method for javascript get class name that I find super reliable: using Object.prototype.toString.call().

const obj = new Date();
console.log(Object.prototype.toString.call(obj)); // "[object Date]"

You get a string like [object Date], and from there, you can extract the type. It’s a bit lower-level, but really powerful when you want to accurately check different object types in your javascript get class name logic, especially in bigger, dynamic applications.

Both of those are spot on! From my side, after a few years of writing utility libraries, I realized that wrapping the logic into a helper function makes life easier, especially for reusable code where you often need javascript get class name checks.

function getClassName(obj) {
  return obj?.constructor?.name || 'Unknown';
}

const item = new Map();
console.log(getClassName(item)); // "Map"

It’s safe, a bit defensive, and super handy when you’re trying to standardize how you do javascript get class name checks across multiple files or modules. I always tuck this into a utils folder—can’t imagine a project without it now!