javascript
  1. javascript-isarray

JavaScript isArray()

The JavaScript isArray() method is used to check whether a given value is an Array or not. This method returns a boolean value - true if the value is an Array, and false otherwise.

Syntax

The syntax for isArray() method is:

Array.isArray(value)

Here, value is the value that needs to be checked.

Example

Consider the following example:

const arr = [1, 2, 3];
const str = "Hello World!";

console.log(Array.isArray(arr)); // true
console.log(Array.isArray(str)); // false

Output:

true
false

Explanation

In the above example, Array.isArray(arr) returns true because arr is an array, whereas Array.isArray(str) returns false because str is not an array.

Use

The isArray() method can be used to check if a value is an array before performing array-specific operations on it. It can also be used in conjunction with other array methods to handle edge cases.

Consider the following example:

const fruits = ["apple", "banana", "orange"];

if (Array.isArray(fruits)) {
  fruits.forEach((fruit) => console.log(fruit));
}

Output:

apple
banana
orange


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array and forEach Example</title>
</head>
<body>

<script>
    // Array example
    const fruits = ["apple", "banana", "orange"];

    // Check if the variable is an array
    if (Array.isArray(fruits)) {
        // Use forEach to loop through each element and log it
        fruits.forEach((fruit) => document.write("<p>" + fruit + "</p>"));
    } else {
        document.write("<p>Not an array</p>");
    }
</script>

</body>
</html>
Try Playground

In this example, isArray() is used to check if fruits is an array before invoking the forEach() method on it.

Important Points

Here are some important points to keep in mind while using isArray() method:

  • The isArray() method is a static method of the Array constructor, which means that it is called directly on the Array constructor itself, rather than on an instance of the Array object.
  • The isArray() method works in all modern browsers, including IE9 and above.
  • Just because the isArray() method returns true does not necessarily mean that the object is a true Javascript array. For example, NodeList or HTMLCollection objects returned by querySelectorAll() method have most of the properties and methods of an array, but they are not actual arrays, andisArray(Nodelist) returns false.

Summary

The isArray() method is a useful JavaScript method for checking whether a given value is an array or not, returning a boolean value true or false. It can be used to handle edge cases and perform array-specific operations with greater confidence and control.

Published on: