The isArray()
method checks whether the passed argument is an array or not.
Example
let numbers = [1, 2, 3, 4];
// checking whether numbers is an array or not
console.log(Array.isArray(numbers));
let text = "JavaScript";
// checking whether text is an array or not
console.log(Array.isArray(text));
// Output:
// true
// false
isArray() Syntax
The syntax of the isArray()
method is:
Array.isArray(value)
The isArray()
method, being a static method, is called using the Array
class name.
isArray() Parameters
The isArray()
method takes a single parameter:
- value - The value to be checked.
isArray() Return Value
The isArray()
method returns:
true
if the passed value isArray
false
if the passed value is notArray
Note: This method always returns false for TypedArray
instances.
Example 1: Using isArray() Method
let fruits = ["Apple", "Grapes", "Banana"];
// checking whether fruits is an array or not
console.log(Array.isArray(fruits));
let text = "Apple";
// checking whether text is an array or not
console.log(Array.isArray(text));
Output
true false
In the above example, we have used the isArray()
method to find out whether fruits and text are arrays or not.
(Array.isArray(fruits))
returns true
since fruits is an array object and (Array.isArray(text))
returns false
since text is not an array (it's a string).
Example 2: isArray() to Check Other Data Types
// passing an empty array []
console.log(Array.isArray([])); // true
// we have created an array with element 7 and
// passed that value to isArray()
console.log(Array.isArray(new Array(7))); // true
// passing a boolean value
console.log(Array.isArray(true)); // false
// passing undefined
console.log(Array.isArray(undefined)); // false
// not passing any argument in isArray()
console.log(Array.isArray()); // false
Output
true true false false false