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);  // false

The 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; // true

A Dog instance is also an Animal instance because Dog extends Animal. The operator follows the prototype chain.

Important limitations

Related topics