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


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

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

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

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

Checking object is of array type or not

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

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

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

Object constructor

Object constructor name return type of the object like an object,Number,String,Array. the following checks constructor name is 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 an objects, This is part of native method in javascript language, installation of libraries are not required. Only drawback with this is older browsers support. return true - if it is array, false- not anarray

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] (https://caniuse.com/#search=isArray)

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

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

Jquery isArray Method

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

Syntax and example

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

underscorejs, lodash isArray Method

Incase, if your project is using underscorejs library, isArray method returns true - for array,false -for other typescript

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

same code works in lodashJs projects

AngularJS object check of array type

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

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