W3jar
320 words
2 minutes

How to Get the Class Name of an Object in JavaScript

In JavaScript, getting the class name of an object can be done in a few different ways, depending on whether you’re working with built-in objects or custom classes. Here’s how you can get the class name of an object:

1. Using the constructor.name Property#

If you have a custom class, you can retrieve its name using the constructor.name property of the instance.

class MyClass {
    // class definition
}

const instance = new MyClass();
console.log(instance.constructor.name); // Output: "MyClass"

For built-in objects, such as Array, Date, or RegExp, this will also return the class name:

const date = new Date();
console.log(date.constructor.name); // Output: "Date"

const arr = [];
console.log(arr.constructor.name); // Output: "Array"

2. Using Object.prototype.toString()#

For a more generic approach that works for both custom classes and built-in types, you can use Object.prototype.toString() method. This method returns a string in the format [object Type], where Type is the class name.

function getClassName(obj) {
    return Object.prototype.toString.call(obj).slice(8, -1);
}

class MyClass {
    // class definition
}

const instance = new MyClass();
console.log(getClassName(instance)); // Output: "MyClass"

const arr = [];
console.log(getClassName(arr)); // Output: "Array"

3. Handling Prototypes#

For objects created from prototypes, constructor.name and Object.prototype.toString will still provide accurate class names if the prototype chain is not altered. However, if you dynamically set prototypes or modify the constructor property, you may get unexpected results.

4. In a Browser Environment#

In a browser, you can also check the class name directly in the developer console by logging the object and examining its properties.

Examples#

class MyClass {
    // class definition
}

const instance = new MyClass();
console.log(instance.constructor.name); // Output: "MyClass"

const obj = {};
console.log(Object.prototype.toString.call(obj)); // Output: "[object Object]"

Summary#

  • constructor.name: Best for getting the class name directly, works well with custom classes and built-in objects.
  • Object.prototype.toString.call(obj): Provides a generic way to get the class name, works reliably for built-in types and objects created from prototypes.

Choose the method that fits your use case based on the type of objects you are dealing with and the environment in which your code is running.