DEV Community

loading...

How to Check if a JavaScript Object is an Array

aumayeung profile image John Au-Yeung Originally published at thewebdev.info ・1 min read

Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62

Subscribe to my email list now at http://jauyeung.net/subscribe/

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Third Party Libraries

Underscore and Lodash also have equivalent array check functions:

const arr = [1,2,3,4,5];
const isArraAnArray _.isArray(arr); // true
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

pic
Editor guide
Collapse
taufik_nurrohman profile image
Taufik Nurrohman
return '[' === JSON.stringify(arr).slice(0, 1);
Enter fullscreen mode Exit fullscreen mode