How to use JavaScript instanceof operator? [SOLVED]


Written by - Olorunfemi Akinlua
Reviewed by - Deepak Prasad

What is JavaScript instanceof operator?

As a developer, you may often find yourself in a situation where you need to determine the type of an object in your JavaScript code. This is where the instanceof operator comes in handy. By using instanceof, you can easily check if an object is an instance of a particular constructor or class.

This is especially useful when working with inheritance in JavaScript, as it allows you to accurately determine the type of an object even when it is a subclass of another object.

In this article, we will explore the instanceof operator in-depth and provide examples of how it can be used in your code.

 

Using the instanceof operator

The instanceof operator is a way to check if an object is an instance of a particular class or constructor. It is often used to check the type of an object at runtime.

Here is an example of how to use the instanceof operator:

function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
}

const myCar = new Car("Honda", "Accord", 2020);

console.log(myCar instanceof Car);

Output

true

In the example above, we have a Car constructor function that creates car objects. We use the new keyword to create a new instance of the Car class, and assign it to the myCar variable.

Then, we use the instanceof operator to check if myCar is an instance of the Car class. Since myCar was created using the Car constructor, the instanceof operator returns true.

The instanceof operator is useful for determining the type of an object, especially when working with inheritance in JavaScript. For example, if we have a Vehicle class that is the parent class of the Car class, we can use the instanceof operator to check if an object is an instance of either class:

console.log(myCar instanceof Vehicle);

Output

true

In this case, the instanceof operator would return true because the Car class inherits from the Vehicle class.

Here's another example of how to use the instanceof operator

function Cat(name) {
    this.name = name;
}

const cat1 = new Cat("Fluffy");
console.log(cat1 instanceof Cat);
console.log(cat1 instanceof Object);

const cat2 = { name: "Fluffy" };
console.log(cat2 instanceof Cat);
console.log(cat2 instanceof Object);

Output

true
true
false
true

In the example above, we define a Cat constructor function and create a new Cat object called cat1 using the new operator. We then use the instanceof operator to check whether cat1 is an instance of the Cat constructor and the Object constructor.

The instanceof operator returns true if the object is an instance of the specified constructor, and false otherwise. In the example above, cat1 is an instance of both the Cat constructor and the Object constructor, so both checks return true.

On the other hand, cat2 is not an instance of the Cat constructor, since it was not created using the new operator. However, it is still an instance of the Object constructor, since all objects in JavaScript are descended from the Object prototype.

 

Working with object

Here's another example that demonstrates how the instanceof operator can be used to check the type of an object

const arr = [1, 2, 3];
console.log(arr instanceof Array);
console.log(arr instanceof Object);

const date = new Date();
console.log(date instanceof Date);
console.log(date instanceof Object);

const error = new Error("Something went wrong");
console.log(error instanceof Error);
console.log(error instanceof Object);

Output

true
true
true
true
true
true

In this example, we create an array, a date, and an error object, and use the instanceof operator to check their types. As expected, the arr variable is an instance of the Array constructor and the Object constructor, the date variable is an instance of the Date constructor and the Object constructor, and the error variable is an instance of the Error constructor and the Object constructor.

 

Working with primitive values

It's important to note that the instanceof operator only works with objects that were created using a constructor function. If you try to use it with a primitive value (such as a number or a string), it will always return false.

Here's an example of how the instanceof operator behaves with primitive values:

console.log(1 instanceof Number); // Output: false
console.log('foo' instanceof String); // Output: false
console.log(true instanceof Boolean); // Output: false

In all of these cases, the instanceof operator returns false, since 1, 'foo', and true are all primitive values and not objects.

 

Summary

The instanceof operator in JavaScript is used to determine if an object is an instance of a particular constructor or class. It checks the object's prototype chain and returns true if the constructor appears anywhere in the chain. This is useful for determining the type of an object, particularly when working with inheritance.

However, it is important to note that instanceof does not work with primitive values and will always return false for them. It is also not reliable for checking the type of objects from other frames or windows, as it only checks the prototype chain within the current context.

In summary, the instanceof operator is a useful tool for determining the type of an object in JavaScript, but it has some limitations that developers should be aware of.

 

References

instanceof - JavaScript | MDN (mozilla.org)
What is the instanceof operator in JavaScript? - Stack Overflow

 

Views: 0

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on LinkedIn.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment