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:
javascript
obj instanceof Constructorobj— 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
javascript
function Animal() {}
function Dog() {}
const rex = new Dog();
console.log(rex instanceof Dog); // true
console.log(rex instanceof Animal); // falseIf 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
javascript
typeof [] // "object"
[] instanceof Array // trueConclusion
- 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.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.