JavaScript(JS) array method - isarray

htt‮‬ps://www.theitroad.com

The Array.isArray() method is a static method in JavaScript that determines whether the passed value is an array or not. It returns true if the value is an array, and false otherwise.

Here's the syntax of the Array.isArray() method:

Array.isArray(value);
  • value is the value to be checked.

The Array.isArray() method returns a boolean value (true or false).

Here's an example of how to use the Array.isArray() method:

let array = [1, 2, 3, 4, 5];
let notArray = "hello";

console.log(Array.isArray(array)); // true
console.log(Array.isArray(notArray)); // false

In this example, we have an array array containing the elements [1, 2, 3, 4, 5], and a variable notArray containing the string "hello". We use the Array.isArray() method to check whether array and notArray are arrays or not. The output of this code will be:

true
false

Note that the Array.isArray() method was introduced in ECMAScript 5, so it may not be supported by older browsers. If you need to achieve the same functionality in older browsers, you can use the following code:

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

console.log(isArray(array)); // true
console.log(isArray(notArray)); // false

This code defines a function isArray() that uses the toString() method of the Object.prototype object to check whether the passed value is an array or not.