JavaScriptArrays
Array. isArray()
Checks whether a value is an array.
- Returns
trueorfalse.- Changes the original
- No
Example
#JavaScript
console.log(Array.isArray([1, 2]))
console.log(Array.isArray({ length: 2 }))
console.log(Array.isArray('text'))
console.log(typeof [1, 2])Console
true
false
false
object
Definition and usage
#The static Array.isArray() method returns true if the given value is an array, and false in every other case.
It’s needed because the typeof operator returns "object" for arrays, just like for plain objects and null. You can’t tell them apart that way.
It comes in handy with data from outside the app, for example from an API or a JSON file, where a field might be a single value or a list.
Syntax
#Syntax
Array.isArray(value)Parameters
#value
any value
The value to check.
More examples
#JavaScript
const toList = (value) => (Array.isArray(value) ? value : [value])
console.log(toList('HTML'))
console.log(toList(['HTML', 'CSS']))Console
['HTML']
['HTML', 'CSS']
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Don’t check for arrays with
typeof. It always returns"object". - A function that turns a single value into an array (
toList) simplifies handling data from forms and APIs.
Related entries
#Spotted a mistake or missing an example? Write to us.