How to Get a Class Name of an Object

As there is no direct getClass() 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 return a string
function Func() {} let func = new Func(); typeof Func; // == "function" typeof fonc; // == "object" console.log(typeof Func); console.log(typeof func);

instanceof

The instanceof operator is used for checking whether the constructor's prototype property appears anywhere in the object's prototype chain. Use the name property of the constructor function to get the name of the class:

Javascript instanceof operator check the constructor's prototype property
function Func() {} let func = new Func(); console.log(Func.prototype.isPrototypeOf(func)); // == true console.log(func instanceof Func); // == true console.log(func.constructor.name); // == "Func" console.log(Func.name); // == "Func"

isPrototypeOf

The isPrototypeOf() method is used to check whether an object exists in another object's prototype chain:

Javascript isPrototypeOf method check an object exists in another object's prototype
function Func() {} let func = new Func(); console.log(Func.prototype.isPrototypeOf(func)); // == true

prototype

You can use the prototype property for getting the name of the object class:

Javascript prototype property get the name of object class
function Func() {} let func = new Func(); Func.prototype.bar = function (x) { return x + x; }; console.log(func.bar(11)); // == 22

JavaScript Objects

The Object class represents one of the data types in JavaScript. It is used to store various keyed collections and complex entities. Almost all objects in JavaScript are instances of Object; a typical object inherits properties (as well as methods) from Object.prototype, though they may be overridden.