Javascript Example Top Five ways to check Object is an array?

In this article, You’ll learn about the number of ways to check whether an object is an array or not.

You can check my previous post.

In javascript, there is no type checking, declared variable holds any type of data including an array of any type. We need to know the object type based on the data stored.

There are many ways to check whether the object type is an array or not in javascript.

  • Object constructor
  • Array isArray native method
  • Jquery isArray Method
  • lodashJs & underscore js library isArray method
  • Angular isArray method

Checking whether an object is of array type or not

Let’s declare the following two objects, One is an array other is a String

let objArray = [1, 5, 61];
let obj = "stringvalue";

Based on your project library usage, you can choose one method from the following ways.

Object constructor

Object constructor name returns the type of the object like an object, Number, String, and Array. the following checks constructor name is an array or not

function isArray(obj) {
  if (obj.constructor.name == "Array") {
    return true;
  }
  return false;
}
console.log(isArray(objArray));
console.log(isArray(obj));

Array isArray method

Array inbuilt-in method isArray checks for objects, This is part of the native method in javascript language, installation of libraries is not required. The only drawback with this is older browsers support. return true - if it is an array, false- not an array

console.log(Array.isArray(objArray)); //true
console.log(Array.isArray(obj)); //false

isArray native method does not support older browsers

isArray caniuse usage support

You can check browsers support for isArray caniuse🔗

If older browsers are not supported, you have to write a polyfill, which adds support for older browsers.

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

Jquery isArray Method

If the application is based on legacy javascript jquery, the isArray method is used.

Syntax and example

jQuery.isArray(object); // syntax
jQuery.isArray(objArray); //true
jQuery.isArray(obj); //false

underscorejs, lodash isArray Method

In case, if your project is using the underscorejs library, the isArray method returns true - for array, false -for other typescripts

console.log(_.isArray(objArray)); //true
console.log(_.isArray(obj)); //false

The same code works in lodashJs projects

AngularJS object check of array type

In AngularJS projects, Global object Angular provides the isArray method to check whether an object contains an array type or not.

var values = [
  { id: "1", name: "Franc" },
  { id: "2", name: "John" },
];
angular.isArray(values); // true