How to check if a JavaScript value is an array?
By Flavio Copes
Learn how to determine if a JavaScript value is an array using the Array.isArray() static method, which returns true only for real arrays.
Use Array.isArray(). It returns true when the value is a real array, and false for everything else.
Sometimes you got passed an object in a function, and you need to check if this is an array.
Maybe if it’s an array you perform some operation, and if it’s not an array you perform something else.
Array.isArray() is a static method provided by the Array built-in object, introduced in ECMAScript 5:
const list = [1, 2, 3]
Array.isArray(list) //true
It works on any value, and it never throws:
Array.isArray('test') //false
Array.isArray({ length: 3 }) //false
Array.isArray(null) //false
Why not typeof?
Because typeof can’t tell arrays apart from plain objects. Arrays are objects in JavaScript:
typeof [1, 2, 3] //'object'
typeof { city: 'Rome' } //'object'
Both give you 'object', so the check tells you nothing useful here.
Why not instanceof?
list instanceof Array returns true, and in most code it works fine. But it breaks in one specific scenario: values created in another realm, like an iframe. Each iframe has its own Array constructor, so an array built there is not an instance of your page’s Array, and the check returns false.
Array.isArray() was introduced to solve exactly this. It gives the right answer no matter where the array was created.
A practical use
The typical case for me: a function parameter that accepts one item or a list of items. You normalize it at the top and the rest of the function only deals with arrays:
function addTags(post, tags) {
if (!Array.isArray(tags)) {
tags = [tags]
}
tags.forEach(tag => post.tags.push(tag))
}
addTags(post, 'javascript')
addTags(post, ['javascript', 'node'])
Both calls work, and there’s no duplicated logic for the two cases.
Watch out for array-like objects
Some values look like arrays but aren’t. A NodeList returned by document.querySelectorAll() has a length and numeric indexes, but Array.isArray() correctly returns false for it, and it’s missing methods like map().
If you need a real array, convert it with Array.from():
const items = Array.from(document.querySelectorAll('li'))
Array.isArray(items) //true
After the conversion, every array method is available.
Related posts about js: