This post will discuss how to determine whether an object is an array in JavaScript and jQuery.

The arrays in JavaScript can be created using the Array() constructor or Array literal notation. To determine whether a given object is an array, we can use any of the following functions in JavaScript:

1. Using Array.isArray() function

The standard function to determine whether the specified object is an array is with the Array.isArray() function, which is a built-in function that returns true if the given value is an array, and false otherwise.

Download  Run Code

2. Using Object.prototype.toString() function

Another option is to use call the Object.prototype.toString() function, which is a built-in function that returns a string representation of the object’s type. We can use this function to compare the object’s type with the string "[object Array]", which is the standard type for arrays. The approach is used internally by the Array.isArray() function. For instance:

Download  Run Code

3. Using instanceof operator

We can also use the instanceof operator, which is a built-in operator that tests if an object is an instance of a constructor function. We can use this operator to check if an object is an instance of the Array constructor function, which creates array objects.

Download  Run Code

 
Alternatively, we can check if the value of the object constructor is the same as the standard built-in Array constructor. The !! operator should be used first to check if the object is truthy.

Download  Run Code

4. Using Underscore/Lodash Library

We can use the _.isArray() function from the Underscore/Lodash library, which returns true if the given value is an array, and false otherwise. This function offers the same functionality as the Array.isArray() function.

Download Code

5. Using jQuery library

With jQuery library, we can use the jQuery.isArray() function to check whether the given object is a JavaScript array. It returns true if the given value is an array, and false otherwise.

Download Code

That’s all about checking if an object is an array in JavaScript and jQuery.