Check if Array in JS

Table of Contents

Check if Array in JS

The Array class has a function on it called isArray() which can be used to check if something is an array.

> Array.isArray('Hello, World!');
// => false

> Array.isArray(['One', 2, [3]]);
// => true

> Array.isArray({ foo: 'bar' });
// => false

> Array.isArray([]);
// => true

The MDN docs provide an example polyfill if it is not natively available.

if (!Array.isArray) {
  Array.isArray = function (arg) {
    return Object.prototype.toString.call(arg) === "[object Array]";
  };
}