SourceBae Blogs

The Instanceof Operator in JavaScript: Syntax, Examples

In JavaScript, the instanceof operator is used to check if an object is an instance of a particular constructor or class. The instanceof operator compares the prototype property of the constructor with the prototype property of the object’s constructor. In this article, we will explore the syntax, examples, and explanation of the instanceof operator in JavaScript.

The Instanceof Operator in JavaScript

1. Syntax:

The instanceof operator is written with the instance to be checked on the left-hand side and the constructor on the right-hand side.

object instanceof constructor

2. Examples:

class Person { } let person = new Person(); console.log(person instanceof Person); // Output: true console.log(person instanceof Object); // Output: true console.log(person instanceof Array); // Output: false
let numbers = [1, 2, 3]; console.log(numbers instanceof Array); // Output: true console.log(numbers instanceof Object); // Output: true console.log(numbers instanceof String); // Output: false

3. Explanation:

The instanceof operator compares the prototype property of the constructor with the prototype property of the object’s constructor, it returns true if they match and false otherwise.

The prototype property of the constructor is the object that is assigned to the prototype property of the constructor function when it’s defined. When an object is created by a constructor function, its internal prototype property is set to the prototype property of the constructor function.

It’s important to note that the instanceof operator only works with objects and constructor functions defined in the same global context, if objects or constructors are from different contexts or frames, they will not match even if they are of the same constructor.

Conclusion:

The instanceof operator in JavaScript is a powerful tool for determining the type of an object. It compares the prototype property of the constructor with the prototype property of the object’s constructor, and it returns true if they match, false otherwise.

It’s a simple and easy way to check the type of an object, and it’s widely used in many programming scenarios. Understanding how to use the instanceof operator in JavaScript is essential for any JavaScript developer. It’s also important to note its limitations and usage in cross-context or frames scenarios.

Share your love
Sourceblogs
Sourceblogs

India’s Leading Talent Marketplace For Remote Developers.

Leave a Reply

Your email address will not be published. Required fields are marked *