Javascript is array example| Check variable is an array

The array is a collection of fixed-size of elements.

Arrays in javascript declared with the below approaches

var myarray = [];
(or)
myarray = new Array();

These are declared with values in square brackets.

let arr = ["one", "two"];

This tutorial shows you multiple ways to check given variable is an array or not

How do I check if a variable is an array in JavaScript?

There are multiple ways we can check a given variable is an array.

  • constructor property

Javascript contains constructor🔗 property, returns the references of a given object constructor function. It is derived from the Constructor prototype property. Same way, it returns Array as a value for Array variables Here is an example

let arr = ["one", "two"];
let obj = { id: 1 };
console.log(arr.constructor === Array); // true
console.log(obj.constructor === Array); // false

It supports all browsers and its performance is very good.

This is useful for checking variables of Array and Objects only

  • instanceOf operator

instanceOf operator checks given variable is of a given type Array or Objects.

It checks left side variable’s object prototype chain is equal to the right-hand type prototype value.

Here is an example

let arr = ["one", "two"];
let obj={"id":1}
console.log(arr instanceof Array)// true
console.log(obj instanceof Array)// false

It is useful for checking Array and Object variable types.

  • Object prototype call method This is one of the approaches that work for all types. Object.prototype.toString.call for arrays return [object Array]. This works for all variable types. You can also check for the String and number.
console.log(Object.prototype.toString.call(arr)=='[object Array]')// true
console.log(Object.prototype.toString.call(obj)=='[object Array]')// false
  • EcmaScript is Array ES5 introduced the isArray method in the Array class. This works for arrays
console.log(Array.isArray(arr))// true
console.log(Array.isArray(obj))// false
  • Array Prototype property It is another way of setting a property to Array.prototype as given below
Array.prototype.isArray = true;

Next, It returns true for arrays.

console.log(arr.isArray)// true
console.log(obj.isArray)// undefined
  • jquery isArray

In Jquery-based Applications, isArray is useful and returns true for Array types and false for other types.

let arr = ["one", "two"];
let obj={"id":1}
console.log($.isArray(arr))// true
console.log($.isArray(obj))// false
  • underscoreJS isArray underscoreJS is a utility library that contains the isArray function Returns true for arrays and false for other variable types
let arr = ["one", "two"];
let obj={"id":1}
console.log(_.isArray(arr))// true
console.log(_.isArray(obj))// false

Conclusion

There are multiple ways to check given variable is an array or not. Easiest way to check constructor property that retutnrs Array value, check this value in conditional if for checking.