How to check if given object is array in javascript

Learn how to check if given object is array in javascript.

One of the most complicated thing in javascript is to check if the current data is of array type or not, because almost everything in javascript is object.

Using isArray() method.

Array.isArray() method returns a boolean determining if current value is array or not. It will return true if it is array, otherwise false.

let arr = [1, 2, 3];

Array.isArray(arr);
//true

Array.isArray('string');
//false

Array.isArray({abc: 'xyz'});
///false

This works well for normal array, but it will always return false for the typed arrays.

If your browser does not supports Array.isArray() method then you can use this function instead.

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