JavaScript Reference ยท Array
Array.isArray()
Reference for JavaScript Array.isArray(): reliably test whether a value is an array, why typeof and instanceof are not enough, and edge cases.
Array.isArray() returns true if a value is an array and false for everything else. It is the correct way to check for arrays, because typeof [] is just "object", the same as for plain objects and null.
It works for arrays created in other realms, such as an iframe, where instanceof Array fails.
Array.isArray([1, 2]); // true Array.isArray({ length: 2 }); // false
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Array.isArray(value)
| Name | Description |
|---|---|
value |
The value to test. Any type is allowed. |
Return value: true if value is an array (including subclass instances and proxies of arrays), otherwise false.
Exceptions: none. It never throws for a normal value.
Usage notes
- Array-likes are not arrays.
arguments,NodeList, strings and typed arrays returnfalse. Convert them withArray.from()first. - Better than
instanceof.value instanceof Arrayisfalsefor arrays that come from another window or iframe, because each realm has its ownArray.Array.isArray()handles it. - Subclasses and proxies: both return
truewhen the underlying target is an array. - Narrowing in TypeScript:
Array.isArray()acts as a type guard. - Empty and sparse arrays are still arrays:
Array.isArray([,,,])istrue. - Typical uses: normalizing an argument that may be one item or a list, recursive flattening, and validating parsed JSON.
- Not a deep check: it says nothing about the type of the elements.
Browser support
Array.isArray() is supported in every current browser and JavaScript runtime.
Related
Array.from(),Array.of()typeof,instanceof- Lessons: Arrays, Data types, Type conversion