How to Check If an Object is an Array in JavaScript

08/02/2021

Contents

In this article, you will learn how to check if an object is an array in JavaScript.

Checking if an object is an array in JavaScript

In JavaScript, you can use several methods to check if an object is an array. Arrays are a special type of object in JavaScript, and there are different ways to differentiate them from regular objects. Here are some methods you can use:

Using the Array.isArray() method

This method checks if a given object is an array and returns a boolean value.

Example

const arr = [1, 2, 3];
console.log(Array.isArray(arr)); // true

const obj = {a: 1, b: 2};
console.log(Array.isArray(obj)); // false

Using the instanceof operator

This operator checks if an object is an instance of a particular class and returns a boolean value. Since arrays are instances of the Array class, you can use this operator to check if an object is an array.

Example

const arr = [1, 2, 3];
console.log(arr instanceof Array); // true

const obj = {a: 1, b: 2};
console.log(obj instanceof Array); // false

Using the Object.prototype.toString() method

This method returns a string representation of the object’s class. For arrays, the string representation is “[object Array]”. You can use this method to check if an object is an array by comparing the string representation.

Example

const arr = [1, 2, 3];
console.log(Object.prototype.toString.call(arr) === '[object Array]'); // true

const obj = {a: 1, b: 2};
console.log(Object.prototype.toString.call(obj) === '[object Array]'); // false

Using the Array.from() method

This method creates a new array from an array-like object. If the object is not an array, this method will throw a type error. Therefore, you can use this method to check if an object is an array by catching the type error.

Example

const arr = [1, 2, 3];
console.log(Array.from(arr)); // [1, 2, 3]

const obj = {a: 1, b: 2};
try {
  console.log(Array.from(obj));
} catch (e) {
  console.log(e instanceof TypeError); // true
}