Definition and Usage
The Array.isArray()
function is used to check if a given value is an array.
It returns true
if the provided argument is an array, and false
otherwise.
Basic Example
const arr = [1, 2, 3];
const obj = {name: "John Doe"};
console.log(Array.isArray(arr)); // true
console.log(Array.isArray(obj)); // false
Syntax
Array.isArray(value);
The value
parameter is the value to be checked whether it is an array.
Returns true
if value
is an array; otherwise, returns false
.
Examples
// All return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array("a", "b", "c", "d"));
Array.isArray(new Array(3));
// All return false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray("Array");
Array.isArray(true);
Array.isArray(false);
Notes and Considerations
Don't Use the typeof
Operator to Check for Arrays
The typeof
operator returns a string indicating the type of a variable. However, when used on an array, it returns "object"
. Therefore, you cannot reliably determine whether a value is an array using only typeof
console.log(typeof [1, 2, 4]); // Output: "object"
For this reason, the most accurate way to check for arrays in JavaScript is to use the Array.isArray()
function.
Array-like Objects
avaScript has array-like objects, which resemble arrays but are not actual arrays. Examples include the arguments
object and DOM elements like NodeList
. The Array.isArray()
function returns false
for these objects, so be careful when working with them.
function checkArray(arr) {
if (Array.isArray(arr)) {
console.log("It is an array.");
} else {
console.log("It is not an array.");
}
}
const argumentsObj = (function() {return arguments;}());
checkArray(argumentsObj); // Output: "It is not an array."
Specifications
Specification | |
---|---|
Array.isArray()
|
ECMAScript Language Specification #sec-array.isarray |
Browser compatibility
Method |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
Array.isArray()
|
4 | 12 | 4 | 10.5 |