How can I check if an object is an array

How to Check if an Object is an Array in JavaScript

If you are working with JavaScript, you might need to check if a variable is an array or not. This can be done using several methods. Here's how:

Method 1: Using instanceof operator

The easiest way to determine if an object is an array is by using the instanceof operator.


    var arr = [1,2,3];
    if(arr instanceof Array) {
      console.log("arr is an array");
    }
  

Method 2: Using Array.isArray() method

An alternative method to check if an object is an array is to use the Array.isArray() method.


    var arr = [1,2,3];
    if(Array.isArray(arr)) {
      console.log("arr is an array");
    }
  

Method 3: Using Object.prototype.toString.call() method

The third method is to use the Object.prototype.toString.call(). This method returns a string representation of the object's type, which can be used to check if it's an array.


    var arr = [1,2,3];
    if(Object.prototype.toString.call(arr) === '[object Array]') {
      console.log("arr is an array");
    }
  

Using any of these methods, you can easily determine if an object is an array or not.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe