Javascript instanceof operator
Created By: chatGPT
The
instanceof
operator in JavaScript is used to check whether an object is an instance of a specific constructor or class. It returns a boolean value: true
if the object is an instance, and false
otherwise. This is particularly useful for determining the type of an object at runtime.// Example of `instanceof` operator
function Car(make, model) {
this.make = make;
this.model = model;
}
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar instanceof Car); // true
console.log(myCar instanceof Object); // true
console.log(myCar instanceof Array); // false
Using
instanceof
with built-in constructors like Array
, Date
, and Function
can help in navigating complex data structures. Remember that instanceof
checks the prototype chain, so it verifies not only the immediate constructor but also its inherited prototypes.// Example with built-in constructors
const myArray = [1, 2, 3];
const myDate = new Date();
console.log(myArray instanceof Array); // true
console.log(myArray instanceof Object); // true
console.log(myDate instanceof Date); // true
console.log(myDate instanceof Array); // false
Caution with
instanceof
when dealing with different execution contexts (like iframes). Objects created in one context won't be recognized as instances when inspected in another, leading to unexpected results.// Caution with multiple contexts
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
const iframeArray = iframe.contentWindow.Array;
const newArray = new iframeArray(1, 2, 3);
console.log(newArray instanceof Array); // false
console.log(newArray instanceof iframeArray); // true
Custom objects can also be checked with
instanceof
. This is helpful when you create your own object types and want to ensure that your logic correctly identifies them.// Example with a custom object
class Animal {
constructor(type) {
this.type = type;
}
}
const dog = new Animal('Dog');
console.log(dog instanceof Animal); // true
console.log(dog instanceof Object); // true