We will start by going over the syntax of the Array isArray() method.
Observe the syntax of the Array isArray() below:
In this syntax:
- Object is the argument, the one we want to determine as an array or not
- Boolean: Returns true if the object passed to this method was actually an array otherwise it would return false
Example 1: Passing an Array to Array.isArray() Method
To demonstrate the working of this method, first create an array of the same types of values with the help of the following line:
After that, pass this array to the Array.isArray() method and store the return value in a new variable named as the result:
After that, simply display the value inside the result variable on the terminal using the console log function:
Execute the code, and observe the output to be:
The output shows that the object passed to this method was actually an array.
Example 2: Passing an Array With Different Data Type Values
To check whether this method works with an array containing values of different data types, create an array using the following line:
Pass this object into the Array.isArray() method and store the result in a result variable:
Afterwards, simply print the result from the result variable onto the terminal using the console log() function:
Execute the code and observe the following output:
From the output, it is conclusive that the type of data stored inside the array doesn’t matter. It only checks whether the object is an array or not, which in this case was true.
Example 3: Passing a String Object in Array.isArray() Method
To demonstrate what happens when a non-array object is passed to the Array isArray() method, create a new string variable with the help of the following line:
Pass this string value into the arguments of the Array.isArray() method and store the outcome in a new variable:
Print the value inside the result_var on the terminal using the console log() function:
Execute the program and get the following output on the terminal:
It returns that the object passed into its argument was not an array.
The Array.isArray() method is pretty simple. It simply checks whether the object in its argument is an array or not and returns true or false to the caller. If an array is being passed, the values or even the data types of its values don’t matter. In this article, we have learned about the different outcomes of the Array.isArray() method with the help of different examples.