Skip to main content
Practice Problems

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 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

javascript
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

javascript
typeof [] // "object" [] instanceof Array // true

Conclusion

  • Use instanceof to understand whether an object belongs to a specific type or was created via new 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 — instanceof can behave unpredictably.

Important:

instanceof only works with objects created via new or with explicitly set prototype. Doesn't work with primitives.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems