The instanceof operator in JavaScript is used to check if an object belongs to a particular class or constructor. It returns true if the object is an instance of the specified constructor, and false otherwise.
The instanceof operator is useful for checking the type of an object or whether it inherits from a particular constructor or class. It's important to note that this operator only works with objects created from constructor functions or classes, and it may not behave as expected with objects created through other means.
Checking an Object's Instance of a Constructor Function
In this example, myCar is an instance of the Car constructor, so instanceof returns true.
function Car(make, model) { this.make = make; this.model = model; } var myCar = new Car('Toyota', 'Camry'); console.log(myCar instanceof Car); // true
Checking Inheritance
Here, myDog is an instance of both Dog and Animal since Dog inherits from Animal.
function Animal() { } function Dog() { } Dog.prototype = Object.create(Animal.prototype); var myDog = new Dog(); console.log(myDog instanceof Dog); // true console.log(myDog instanceof Animal); // true
Checking with Custom Objects
All objects in JavaScript inherit from Object, so instanceof Object returns true for any object.
var person = { name: 'John', age: 30 }; console.log(person instanceof Object); // true
Checking with Arrays
Arrays in JavaScript are a type of object, so instanceof Array and instanceof Object both return true.
var myArray = [1, 2, 3]; console.log(myArray instanceof Array); // true console.log(myArray instanceof Object); // true
Checking with User-Defined Objects
The instanceof operator works with constructor functions and class constructors. Here, it returns true because myRectangle is an instance of the Rectangle class.
class Rectangle { constructor(width, height) { this.width = width; this.height = height; } } var myRectangle = new Rectangle(10, 20); console.log(myRectangle instanceof Rectangle); // true