The instanceof Operator in JavaScript

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; obj.width; obj instanceof Rectangle; ({}) instanceof Rectangle;

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; obj instanceof BaseClass;

The Object Class

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

class MyClass {} const obj = new MyClass(); obj instanceof Object ; ({}) instanceof Object ; null instanceof Object ;

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 .

typeof Object .prototype; Object .prototype instanceof Object ; function MyClass ( ) {} MyClass.prototype = Object .create( null ); typeof new MyClass(); ( new MyClass()) instanceof Object ;

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; obj instanceof MyOtherClass; obj instanceof { answer : 42 };

More Fundamentals Tutorials