The instanceof Operator in JavaScript

Aug 28, 2019

The instanceof operator tests whether a given object is an instance of a given JavaScript class.

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

const obj = new Rectangle(3, 5);
obj.height; // 3
obj.width; // 5

// The `instanceof` keyword is how you test whether an object was created
// from a certain class.
obj instanceof Rectangle; // true
({}) instanceof Rectangle; // false

Technically, the instanceof operator checks the prototype chain to see if any constructor in the prototype chain is equal to the given class. That means if you use inheritance, an instance of a subclass is also an instance of the base class.

class BaseClass {}
class SubClass extends BaseClass {}

const obj = new SubClass();

obj instanceof SubClass; // true
obj instanceof BaseClass; // true

The Object Class

The Object class is the base class for all JavaScript classes.

class MyClass {}

const obj = new MyClass();

obj instanceof Object; // true
({}) instanceof Object; // true
null instanceof Object; // false

You might be tempted to use v instanceof Object to check whether v is an object. That works for most cases, but there are several cases where an object is not instanceof Object.

// `Object.prototype` is not technically `instanceof Object` because
// prototype chains must end somewhere
typeof Object.prototype; // 'object'
Object.prototype instanceof Object; // false

// Setting a function's prototype to `Object.create(null)` means
// `Object` won't be in the object's prototype chain.
function MyClass() {}
MyClass.prototype = Object.create(null);

typeof new MyClass(); // 'object'
(new MyClass()) instanceof Object; // false

Error Cases

The instanceof operator throws an error if the right hand side is not a function.

class MyClass {}

function MyOtherClass() {}

const obj = {};

obj instanceof MyClass; // false
obj instanceof MyOtherClass; // false

// Throws "TypeError: Right-hand side of 'instanceof' is not callable"
obj instanceof { answer: 42 };

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials