How to use instanceof operator In Javascript

The instanceof operator is used to test whether the prototype property of a constructor appears anywhere in the prototype chain of an object. This can be used to evaluate if the given variable has a prototype of ‘Array’.

Syntax:

variable instanceof Array

Return value: The operator returns a true boolean value if the variable is the same as what is specified (here an Array) and a false if it is not. This is shown in the example below. 

Example: In this example, we will check if a given variable is an array or not using the instanceof operator in JavaScript. 

Javascript
function checkArray() {
    let str = 'This is a string';
    let num = 25;
    let arr = [10, 20, 30, 40];

    let ans = str instanceof Array;
    console.log("Output for String:" + ans);

    ans = num instanceof Array;
    console.log("Output for Number:" + ans);

    ans = arr instanceof Array;
    console.log("Output for Array:" + ans);
}

checkArray();

Output
Output for String:false
Output for Number:false
Output for Array:true

How to check if a variable is an array in JavaScript?

This article will show you how to check whether the given variable value is an array or not.

Table of Content

  • Using JavaScript isArray() method
  • Using JavaScript instanceof operator
  • Checking the constructor property of the variable
  • Using Object.prototype.toString.call()
  • Checking the Length Property
  • Using Array.prototype.isPrototypeOf()

Similar Reads

Using JavaScript isArray() method

isArray() method checks whether the passed variable is an Array object or not....

Using JavaScript instanceof operator

The instanceof operator is used to test whether the prototype property of a constructor appears anywhere in the prototype chain of an object. This can be used to evaluate if the given variable has a prototype of ‘Array’....

Checking the constructor property of the variable

The constructor property is the another method to check a variable is an array by checking its constructor with Array....

Using Object.prototype.toString.call()

The Object.prototype.toString.call() method can be utilized to determine the type of an object. If the result of this method call is ‘[object Array]’, then the variable is an array....

Checking the Length Property

You can determine if a variable is an array by checking if it has a numeric length property. Non-array objects won’t have this property, or if they do, it won’t represent the number of elements in a collection....

Using Array.prototype.isPrototypeOf()

The Array.prototype.isPrototypeOf() method checks if a variable is an array by determining if Array.prototype exists in the prototype chain of the variable. If it does, the method returns true, confirming the variable is an array....