W3jar
249 words
1 minutes

How to Check if an Object is an Array in JavaScript

To determine whether a value is an array in JavaScript, you can use several methods. Here are the most common and reliable approaches:

1. Array.isArray()#

The Array.isArray() method is the most straightforward and recommended way to check if a value is an array. It returns true if the value is an array, and false otherwise.

const arr = [1, 2, 3];
const obj = { a: 1, b: 2 };

console.log(Array.isArray(arr)); // Output: true
console.log(Array.isArray(obj)); // Output: false

Syntax:

Array.isArray(value);
  • value: The value to check.

2. instanceof Operator#

You can also use the instanceof operator to check if an object is an instance of Array. However, this method can be less reliable in scenarios involving different execution contexts (e.g., iframes).

const arr = [1, 2, 3];
const obj = { a: 1, b: 2 };

console.log(arr instanceof Array); // Output: true
console.log(obj instanceof Array); // Output: false

Syntax:

value instanceof Array;
  • value: The value to check.

3. Object.prototype.toString.call()#

For a more robust solution, especially in cases involving different execution contexts, you can use Object.prototype.toString.call(). This method checks the internal [[Class]] property of the object and returns a string indicating its type.

const arr = [1, 2, 3];
const obj = { a: 1, b: 2 };

function isArray(value) {
    return Object.prototype.toString.call(value) === "[object Array]";
}

console.log(isArray(arr)); // Output: true
console.log(isArray(obj)); // Output: false

Syntax:

Object.prototype.toString.call(value);
  • value: The value to check.

Summary#

  • Array.isArray(): Recommended for most cases; simple and reliable.
  • instanceof Array: Useful but can be problematic with different execution contexts.
  • Object.prototype.toString.call(): Very reliable, especially in complex scenarios.

For most use cases, Array.isArray() is the preferred method due to its simplicity and directness.