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