Categories
JavaScript JavaScript Basics

How to Check if a JavaScript Object is an Array

Spread the love

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *