The JavaScript isArray method is a built-in array method that allows you to check whether a given value is an array. It returns true only if the value is an array and returns false if it is not. ES5 version of Javascript introduced this feature.
Table of Contents
Syntax
The syntax for using the isArray method is as follows.
1 2 3 | Array.isArray(value) |
Parameter
Here, value is the variable or expression you want to check whether it’s an array. The isArray
returns true
if the value is an array and false
otherwise.
IsArray Example
The code below checks various arrays, and the result is always true
.
1 2 3 4 5 6 7 | const numArr = [1, 2, 3]; const strArr = ['hello','world']; console.log(Array.isArray(numArr)); // true console.log(Array.isArray(strArr)); // true |
Returns false
for non-arrays and array-like objects.
1 2 3 4 5 6 7 8 9 10 11 | const num = 123; const str = 'hello'; console.log(Array.isArray(num)); // false console.log(Array.isArray(str)); // false const arrLike = { 0:"Hello", 1:"World", length:2} console.log(arrLike[0]) //Hello console.log(Array.isArray(arrLike)); // false |
isArray vs. InstanceOff
We can also use instanceof to check whether the variable is an array. But both use different techniques to check for an array.
The instanceOf check if an object is an instance of a particular class or constructor function. Due to this, instanceof can give false negatives if you’re checking arrays created in other frames or windows.
You can see from the code below that instanceOf fails to detect an array that we created in a different iframe.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | const iframe = document.createElement("iframe"); document.body.appendChild(iframe); const xArray = window.frames[window.frames.length - 1].Array; const arr = new xArray(1, 2, 3); // [1, 2, 3] // Correctly checking for Array Array.isArray(arr); // true // The prototype of arr is xArray.prototype, which is a // different object from Array.prototype arr instanceof Array; // false |
Hence it is better to use array.isArray()
rather than instanceof because it works across realms.
Summary
- The isArray method allows us to check whether a given value is an array.
- isArray method was introduced in ES5 version of Javascript. If you are using prior version, then use instanceOf.
- The instanceOf operator fails to detect arrays created in different iframe.