What is the instanceof in JavaScript do?

What is the instanceof in JavaScript do?

Hi,

The instanceof operator in JavaScript checks whether an object is an instance of a particular constructor or class.

Basic Usage: The instanceof operator returns true if the prototype property of a constructor appears in the prototype chain of the object.

For example:

function Person() {}
const john = new Person();
console.log(john instanceof Person); // true
console.log(john instanceof Object); // true

instanceof is useful in determining if an object is derived from a particular class. This can be helpful in a class hierarchy.

For instance:

class Animal {}
class Dog extends Animal {}
const dog = new Dog();
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true
console.log(dog instanceof Object); // true

It’s important to note that instanceof will not work as expected with objects from different execution contexts (like iframes). For example:

const arr = new Array();
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true
console.log(arr instanceof Function); // false
// Issue with different execution contexts
const iframeArray = window.frames[0].Array;
const myArray = new iframeArray();
console.log(myArray instanceof Array); // false, if Array is from a different context

The instanceof JavaScript operator is a powerful tool in JavaScript for determining an object’s type and its relationship with constructors and classes, but it should be used carefully, especially in scenarios involving multiple contexts.