What is instanceof operator in JavaScript?
The instanceof operator checks if an object belongs to a class. It also considers the Parent class prototype.
Syntax
object instanceof class
The instanceof operator returns true:
- if the object belongs to the class.
- if the object’s prototype chain contains the class (either the class itself or a parent class).
Otherwise, it returns false.
Example
Let’s create a class like the class structure below.
class Human {}class Man extends Human{}class Woman extends Human {}let man = new Man();let woman = new Woman();console.log("\n--------\nChecking the man object")console.log("man instanceof Man =>", man instanceof Man);console.log("man instanceof Human =>", man instanceof Human);console.log("man instanceof Woman =>", man instanceof Woman);console.log("\n--------\nChecking the Woman object")console.log("woman instanceof Woman =>", woman instanceof Woman);console.log("woman instanceof Human =>", woman instanceof Human);console.log("woman instanceof Man =>", woman instanceof Man);console.log("\n--------\nChecking againts Object")console.log("man instanceof Object=>", man instanceof Object);console.log("woman instanceof Object=>", woman instanceof Object);console.log("\n--------\nPrinting proto chain of man");console.log(man.__proto__);console.log(man.__proto__.__proto__);console.log(man.__proto__.__proto__.__proto__); // Object
In the above code, we have created a Human class and, from that class, we have extended it to create the child classes Man and Woman. An object created from the Man and Woman classes is also an ‘instanceof’ the Human class because the man and woman objects have the Human class in their prototype chain.
If we check the woman object with Man class, then Javascript will check if the woman object has a Man class prototype in their proto chain(proto). It is not there, so the instanceof operator will return false.
Example with Array
let arr = [1, 2, 3];console.log(arr instanceof Array);console.log(arr instanceof Object);