How to Determine if a Variable is an Array

May 14, 2021

You shouldn't use the typeof operator to check whether a value is an array, because typeof cannot distinguish between arrays and objects. Instead you should use Array.isArray(), because typeof would return 'object', not 'array'.

let array = [1,2,3,4];
typeof array; // `object`

Array.isArray() takes one parameter and will return true only if the given value is an array. Anything else will return false. You can also use instanceof to determine if a value is an array, however, Array.isArray() is fullproof as instanceof will not return true on an iframe.

let array = [1,2,3,4];
Array.isArray(array); // true

Note: ES6 introduced the ability to subclass Array, like class CustomArray extends Array {}. The good news is that Array.isArray() will return true for any object that extends Array.

More Fundamentals Tutorials