Loading...
Loading...
The instanceof operator in JavaScript checks whether an object belongs to a specific class (or constructor function) in its prototype chain.
obj instanceof Constructor
obj — the object we're checking.Constructor — constructor function or class.The operator returns true if object obj is in the prototype chain of constructor Constructor.
function Animal() {}
function Dog() {}
const rex = new Dog();
console.log(rex instanceof Dog); // true
console.log(rex instanceof Animal); // false
If Dog inherited from Animal, then rex instanceof Animal would be true.
The instanceof operator works like this:
obj.__proto__.Constructor.prototype.true.__proto__ chain and repeats.typeof [] // "object"
[] instanceof Array // true
instanceof to understand whether an object belongs to a specific type or was created via new SomeConstructor.Object.prototype.toString.call(...) is also popular).instanceof can behave unpredictably.Important:
instanceof only works with objects created via new or with explicitly set prototype. Doesn't work with primitives.