Open In App

How to Check Object is an Array in JavaScript?

Last Updated : 17 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

There are two different approaches to check an object is an array or not in JavaScript.

1. Using Array.isArray() Method

The Array.isArray() method determines whether the value passed to this function is an array or not. This method returns true if the argument passed is an array else it returns false.

Syntax

Array.isArray( obj );
function checkObject() {
    const countries = ["India", "USA", "Canada"];
    const checkArrayObj = Array.isArray(countries);

    console.log(checkArrayObj);
}

checkObject();

Output
true

2. Using instanceof Operator

The instanceof operator tests whether an object is an instance of a specific constructor (in this case, Array). This approach is particularly useful because it checks the prototype chain to determine if an object is derived from Array. The instanceof operator checks if the object (array1 or notArray) has Array in its prototype chain. If it does, it returns true, indicating that the object is indeed an array. Otherwise, it returns false.

Syntax

object instanceof Array
const array1 = [1, 2, 3];
const notArray = { name: 'example' };
console.log(array1 instanceof Array);
console.log(notArray instanceof Array); 

Output
true
false


Similar Reads

three90RightbarBannerImg