How to Get a Class Name of an Object
Read this tutorial and learn information about several methods that are used for getting the class name of the object in JavaScript. Also, try examples.
As there is no direct <kbd class="highlighted">getClass()</kbd> method in JavaScript to get the object’s class name, you can use several options which will help you solve this problem.
typeof
The typeof operator returns a string that indicates the type of the unevaluated operand:
JavaScript typeof operator returns a string
Note: typeof is not reliable for retrieving specific class names, as it typically returns "object" for most custom and built-in objects.
constructor.name
You can use the <kbd class="highlighted">constructor.name</kbd> property of an object to get the name of its class:
JavaScript constructor.name property returns the class name
Note: This method may return "Object" for objects created with Object.create(null) or when the constructor property has been manually overridden.
Object.prototype.toString.call()
The most reliable way to get the class name of any object in JavaScript is using Object.prototype.toString.call(). It returns a string in the format [object ClassName]:
JavaScript Object.prototype.toString.call() method
To extract just the class name, you can use slice():