How to use instanceof Operator In Javascript

The instanceof operator checks if an object is an instance of a particular class or its prototype chain. It’s commonly used to determine the type of an object in JavaScript. This approach is straightforward and widely used, especially when dealing with inheritance hierarchies.

Syntax:

if (object instanceof DerivedClass) {
// Process object as DerivedClass
}

Example: The below example will explain the use of instanceof operator to narrow a type of derived class.

Javascript




interface Animal {
    makeSound(): void;
}
 
class Dog implements Animal {
    makeSound() {
        console.log("Woof woof!");
    }
}
 
class Cat implements Animal {
    makeSound() {
        console.log("Meow meow!");
    }
}
 
const animals: Animal[] = [new Dog(), new Cat(), new Dog()];
 
for (const animal of animals) {
    if (animal instanceof Dog) {
        console.log("Dog instance found");
        animal.makeSound();
    } else if (animal instanceof Cat) {
        console.log("Cat instance found");
        animal.makeSound();
    }
}


Output:

Dog instance found
Woof woof!
Cat instance found
Meow meow!
Dog instance found
Woof woof!

How to Narrow a Type of Derived Class Instances while Processing an Array ?

When it comes to JavaScript arrays that contain derived class instances, narrowing down the types is a must to access the specific functions or properties that are unique to those derived classes. Narrowing encompasses an act of specifically type-checking and casting objects explicitly to their derived types.

Table of Content

  • Using instanceof Operator
  • Using Constructor Property

Similar Reads

Using instanceof Operator

The instanceof operator checks if an object is an instance of a particular class or its prototype chain. It’s commonly used to determine the type of an object in JavaScript. This approach is straightforward and widely used, especially when dealing with inheritance hierarchies....

Using Constructor Property

...

Contact Us