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:
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:
Checking arrays:
Checking non-arrays:
Checking with array-like objects:
- An array-like object (such as
arguments
or DOMNodeList
) is not considered an array:
- An array-like object (such as
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()
:
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.