How to usethe instanceof Operator in Javascript
By utilizing the ‘instanceof’ check in JavaScript, we determine if an object belongs to a particular category, It’s like asking if something is a part of a certain group. For example, employing ‘instanceof’ aids in understanding if an object aligns with a defined type, offering insights into its classification within the code.
Example: In this example we will see how to find the Class Name of an Object Using the instanceof
Operator in JavaScript.
Javascript
class Product { constructor(name) { this .name = name; } // Check if the given object is an // instance of the Product class. isInstanceOfProduct(object) { return object instanceof Product; } } const product = new Product( "Book" ); // Check if the product object is an // instance of the Product class. const isInstanceOfProduct = product.isInstanceOfProduct(product); console.log(isInstanceOfProduct); |
Output:
true
Conclusion :
In JavaScript, determining an object’s class name is essential for understanding its type. Using the constructor property offers a straightforward method, revealing the function that created the object. Meanwhile, the instanceof operator provides a simple way to confirm if the object is an instance of a specific class. Both approaches contribute to identifying the object’s class, aiding in clearer classification and better understanding of its type within the code.
How to get the Class Name of an Object in JavaScript
In this article, we will learn how we can get the class Name of an Object with multiple approaches in JavaScript.
In JavaScript, determining an object’s class name can be done using multiple approaches. The constructor
property of an object reveals the function that created it, while the instanceof
operator checks if an object is an instance of a class. Additionally, employing Object.prototype.toString()
method with the object as an argument helps retrieve its class name in string form. These methods help in identifying the class of an object, help in handling different types of objects within JavaScript programs.
Table of Content
- Using the constructor Property
- Using the instanceof Operator