Instanceof Operator in JavaScript

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.

Instanceof operator

Syntax of using instanceof is as follows

Where object is an object (or an expression that evaluates to an object). constructor is anything that constructs an object. It could be a class or a constructor function.

There are several ways in which we can create an object in JavaScript.

For Example, the following function creates an object person using the constructor function Person.

We want to know whether the Person constructor function created the instance person. This is where we use the instanceof operator. The following code checks if person is created from the Person constructor function.

person Instanceof Object also returns true, this is because the instanceof operator searches the prototype chain of the person object.

How it works

The Instanceof operator compares the prototype of the object with the Prototype Property of the constructor. If they are the same then it returns true. If not it continues to check its prototype chain of the object.

When we run the code person instanceof Person the instanceof operator compares its prototype with the Prototype property of the constructor function. Since they are equal it returns true.

When we check person instanceof Object the instanceof compares the prototype property of the Object (Object.prototype) with the prototype of the person (person.__proto__) object. Since they are not equal it moves up the chain (person.__proto__.__proto__) and then compares it again with Object.prototype. Since they are equal it returns true.

Classes

Classes are another way to create objects.

Object.setPrototypeOf

Note that we can change the prototype of an object after it is constructed.

In the following example, we create the person object from Person function. But later we change its prototype using the Object.setPrototypeOf to Animal function.

Primitive Values

Primitive values are not objects and therefore do not have a Prototype Property. Hence instanceof will not work with them. You can use the Typeof operator for primitive values

Instanceof and multiple context (e.g. frames or windows)

Scripts running in different windows or frames ( <iframe>) gets their own execution environments. This means that they have a different global objects, constructors, etc.

This may result in unexpected results. For instance, [] instanceof window.frames[0].Array will return false, because Array.prototype !== window.frames[0].Array.prototype & arrays inherit from the former.

Reference

Instanceof operator reference

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top