Why instanceof Operator is Needed in JavaScript
What is instanceof
The instanceof operator in JavaScript checks whether an object belongs to a specific class (or constructor function) in its prototype chain.
Syntax:
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.
Example
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.
How it Works
The instanceof operator works like this:
- Takes
obj.__proto__. - Compares it with
Constructor.prototype. - If they match — returns
true. - If not — goes up the
__proto__chain and repeats.
Don't Confuse with typeof
typeof [] // "object"
[] instanceof Array // true
Conclusion
- Use
instanceofto understand whether an object belongs to a specific type or was created vianew SomeConstructor. - It's a powerful tool, but not the only way to check type (e.g.,
Object.prototype.toString.call(...)is also popular). - Be careful in cross-environment scenarios —
instanceofcan behave unpredictably.
Important:
instanceof only works with objects created via new or with explicitly set prototype. Doesn't work with primitives.