JavaScript
This page explains how the instanceof operator checks an object's relationship with a class or constructor function.
Goal: check whether an object is an instance of a class or constructor, and understand what inheritance changes.
The instanceof operator
Use object instanceof Constructor to ask whether an object was created by that constructor or has its prototype in the constructor's prototype chain.
A constructor example
JavaScript
function Person(name, age) {
this.name = name;
this.age = age;
}
const person = new Person("Alice", 25);
console.log(person instanceof Person); // true
console.log(person instanceof Array); // falseThe object created with new Person() is a Person instance, but it is not an array.
Inheritance also affects the result
JavaScript
class Animal {}
class Dog extends Animal {}
const dog = new Dog();
dog instanceof Dog; // true
dog instanceof Animal; // trueA Dog instance is also an Animal instance because Dog extends Animal. The operator follows the prototype chain.
Important limitations
instanceofchecks an object's prototype relationship; it does not inspect whether two objects have the same properties.- Objects created in another JavaScript realm, such as another window or iframe, may not pass an
instanceofcheck as you expect. - For arrays,
Array.isArray(value)is usually clearer and works across realms. - For a data-shape check, validate the properties you actually need instead of relying only on a constructor.