Each JavaScript object has a type.
You can check if an object is an Array in JavaScript using Array.isArray(arr) statement.
Basic Example
const arr = [1, 2, 3];
console.log(Array.isArray(arr)); // Output: true
This tutorial teaches you how to check if an object is an array in JavaScript and when it is appropriate to use each method.
Using Array.isArray() Function
The array.isArray() static method checks if the passed object is an array.
It returns
True
– If the object is an arrayFalse
– If the object is not an array
It is the simplest method to check if an object is an array.
This is the recommended method to check if an Object is an array.
Code
const arr = [1, 2, 3];
console.log(Array.isArray(arr)); // Output: true
const obj = { name: 'John', age: 30 };
console.log(Array.isArray(obj)); // Output: false
Using InstanceOf Operator
The InstanceOf() operator checks if the prototype property of a constructor appears anywhere in the object’s prototype chain.
It’s not suitable to check all types of arrays(Array-like objects). For example, Window.frames.array will return an array-like object. In this case, Array.isArray()
returns True
, whereas the instanceOf
operator returns False
.
Code
The following code demonstrates how to use the InstanceOf()
operator to check if an object is an array.
const arr = [1, 2, 3];
console.log(typeof arr); // Output: object
if (typeof arr === 'object' && arr instanceof Array) {
console.log('The object is an array');
}
Using Constructor Property
The constructor property of the objects points to the constructor function that created the object, and every constructor object has the constructor property.
To check if an object is an array using the constructor
property,
- Invoke the constructor property of the array object and check if it is equal to
Array
Code
const arr = [1, 2, 3];
if (arr.constructor === Array) {
console.log('The object is an array');
}