Code Premix

How can I check if an object is an array in JavaScript

📅June 15, 2023

In this article, we will explore a JavaScript programming technique that enables you to determine whether an object is an array. This knowledge is valuable when working with complex data structures and allows you to handle arrays and non-array objects differently in your code.

By understanding how to identify arrays, you can confidently apply array-specific operations and avoid potential errors when manipulating and accessing array elements.

Methods to check if an object is an array in JavaScript

  1. Using the Array.isArray() method
  2. Using the instanceof operator
  3. Using the Array.prototype.isPrototypeOf() method
  4. Using the Object.prototype.toString() method

1. Using the Array.isArray() method

The Array.isArray() method returns true if the provided object is an array, and false otherwise.

const obj = [1, 2, 3];

if (Array.isArray(obj)) {
  console.log('The object is an array.');
} else {
  console.log('The object is not an array.');
}

2. Using the instanceof operator

The instanceof operator checks if an object is an instance of a particular class or constructor function. In this case, we check if the object is an instance of the Array class, which indicates that it is an array.

const obj = [1, 2, 3];

if (obj instanceof Array) {
  console.log('The object is an array.');
} else {
  console.log('The object is not an array.');
}

3. Using the Array.prototype.isPrototypeOf() method

The isPrototypeOf() method is used to check if an object is in the prototype chain of another object. By calling Array.prototype.isPrototypeOf(obj), we check if the Array.prototype object is in the prototype chain of the given object obj. If it is, then the object is considered an array.

const obj = [1, 2, 3];

if (Array.prototype.isPrototypeOf(obj)) {
  console.log('The object is an array.');
} else {
  console.log('The object is not an array.');
}

4. Using the Object.prototype.toString() method

The toString() method is a generic method available on all objects in JavaScript. When called on an object, it returns a string representation of the object’s type. By using Object.prototype.toString.call(obj), we explicitly call the toString() method from Object.prototype on the given object obj. If the returned string is "[object Array]", it indicates that the object is an array.

const obj = [1, 2, 3];

if (Object.prototype.toString.call(obj) === '[object Array]') {
  console.log('The object is an array.');
} else {
  console.log('The object is not an array.');
}

All of these methods can be used to check if an object is an array in JavaScript. However, the recommended approach is to use the Array.isArray() method as it provides a more straightforward and reliable way to perform the check.

Happy Coding!