JavaScript Array.isArray() method


The Array.isArray() method in JavaScript is used to determine if a given value is an array. It returns true if the value is an array and false if it's not.

Syntax:

Array.isArray(value)
  • value: The value you want to check if it is an array.

Return Value:

  • true: If the provided value is an array.
  • false: If the provided value is not an array.

Example:

  1. Checking arrays:

    console.log(Array.isArray([1, 2, 3])); // true console.log(Array.isArray([])); // true
  2. Checking non-arrays:

    console.log(Array.isArray('Hello')); // false console.log(Array.isArray(123)); // false console.log(Array.isArray({ a: 1 })); // false console.log(Array.isArray(null)); // false
  3. Checking with array-like objects:

    • An array-like object (such as arguments or DOM NodeList) is not considered an array:
    function example() { console.log(Array.isArray(arguments)); // false } example();

Why Use Array.isArray()?

Prior to ES5 (ECMAScript 5), developers used methods like instanceof or Object.prototype.toString.call to check for arrays. However, these methods were not always reliable, especially when dealing with different JavaScript contexts (such as iframe or window objects). Array.isArray() is the preferred and reliable method to detect arrays because it accurately checks across different contexts.

Example with instanceof vs Array.isArray():

let arr = []; console.log(arr instanceof Array); // true console.log(Array.isArray(arr)); // true // However, when dealing with arrays across different frames: let iframeArray = window.frames[0].Array; let arrInFrame = new iframeArray(); console.log(arrInFrame instanceof Array); // false console.log(Array.isArray(arrInFrame)); // true

Summary:

  • Array.isArray() is the reliable and modern way to check whether a value is an array.
  • It handles edge cases that other methods like instanceof do not, making it essential when working across different JavaScript execution environments.