The use instanceof operator allows checking whether an object belongs to a specific class in JavaScript. It also helps to take inheritance into account. This return true in case the object belongs to the Class or the class inherits from it.
obj instanceof Class
JavaScript instanceof Class
A simple example code returns true
if obj
belongs to the Class
or a class inheriting from it.
<!DOCTYPE html>
<html>
<body>
<script>
class Rabbit {}
let rabbit = new Rabbit();
res = rabbit instanceof Rabbit;
console.log("Object of Rabbit class",res)
</script>
</body>
</html>
Output:
Works with constructor functions:
function Rabbit() {}
console.log(new Rabbit() instanceof Rabbit);// true
Check with Arrays
let arr = [1, 2, 3];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true
Both outputs are true because array belongs to the Object class. The reason is that an Array prototypically inherits from Object.
The instanceof
operator is useful when you want to determine the type of an object, especially when working with classes and constructor functions. It checks not only the object’s own constructor but also its prototype chain, so it can be used to check inheritance as well.
Comment if you have any doubts or suggestions on this JS instanceof topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version