How to Check if a JavaScript Object is an Array

There are a few simple ways to check if an object is an array.

Array.isArray

The simplest and easiest way is to use Array.isArray , which are available in most recent browsers, IE9+, Chrome, Edge, Firefox 4+, etc. It is also built into all versions of Node.js. It checks whether any object or undefined is an array.

To use it, do the following:

const arr = [1,2,3,4,5];
const isArrAnArray = Array.isArray(arr); // true
const obj = {};
const isObjAnArray = Array.isArray(obj); // false
const undef = undefined;
const isUndefinedAnArray = Array.isArray(undef); // false

Alternatives

Alternatives include using instanceOf , checking if the constructor is an array or checking if an object’s prototype has the word Array.

Using instanceOf , you can do:

const arr = [1,2,3,4,5];
const isArray = (arr)=>{
return arr.constructor.toString().indexOf("Array") > -1;
}
console.log(isArray(arr)) // true

Similarly, by checking an object’s prototype, you can do:

const arr = [1,2,3,4,5];
const isArray = (arr)=>{
return Object.prototype.toString.call(arr) === '[object Array]';
}
console.log(isArray(arr)) // true

Third Party Libraries

Underscore and Lodash also have equivalent array check functions:

const arr = [1,2,3,4,5];
const isArraAnArray _.isArray(arr); // true
Image for post

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store