How to Check If a Variable is an Array in JavaScript

Arrays in JavaScript are not exact Arrays because are actually Objects. Everything in JavaScript is Objects. So you can’t simply do a typeof check because it will return Object. Then how to check if the value is an array? Well, let’s see how to do that.

JavaScript check if array

To check if it is an array in JavaScript, use the array.isArray() function. The isArray() is a built-in JavaScript method that returns true if an object is an array, otherwise it returns false. The isArray() method is completely supported in all modern browsers.

Syntax

Array.isArray(obj)

Arguments

It takes an obj as a required parameter. It is an object to be tested.

Return Value

It returns a Boolean value. It returns true if the object is an array. Otherwise, it returns false.

Implementation of JavaScript check if array

The Array.isArray() function checks whether the passed value is an Array.

console.log(Array.isArray([11, 21, 19]))

console.log(Array.isArray({ data: 1121 }))

console.log(Array.isArray('dataset'))

console.log(Array.isArray(undefined))

Output

true
false
false
false

You can see that the isArray() function determines if the value is an array or not.

Using instanceof operator

The instanceof is a built-in JavaScript operator that tests to see if the prototype property appears anywhere in the prototype chain of an object. The return value is a boolean value.

let value = [11, 21, 19, 46]

if (value instanceof Array) {
 console.log('The value is an Array!');
} else {
 console.log('It is not an array');
}

Output

The value is an Array!

This approach uses the idea that the Array function is the constructor of the arrays.

Conclusion

To check if the variable is an array or not, use the Array.isArray(value) function. You can not use this function on the ES5+ version. That’s it for this tutorial.

Leave a Comment