Array.isArray()
The Array.isArray()
method in JavaScript is used to determine if a given value is an array. It returns a boolean indicating whether the provided value is an array.
Syntax
</>
Copy
Array.isArray(value)
Parameters
Parameter | Description |
---|---|
value | The value to be checked if it is an array. |
Return Value
The Array.isArray()
method returns true
if the provided value is an array; otherwise, it returns false
.
Examples
1. Checking Arrays
In this example, the method is used to verify if various values are arrays.
</>
Copy
console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray(["a", "b", "c"])); // true
console.log(Array.isArray(new Array(5))); // true
Output
true
true
true
2. Checking Non-Array Values
Non-array values such as objects, strings, and numbers return false
.
</>
Copy
console.log(Array.isArray({ key: "value" })); // false
console.log(Array.isArray("Hello World")); // false
console.log(Array.isArray(42)); // false
Output
false
false
false
3. Checking null
and undefined
Both null
and undefined
are not arrays, so the method returns false
.
</>
Copy
console.log(Array.isArray(null)); // false
console.log(Array.isArray(undefined)); // false
Output
false
false
4. Using Array.isArray()
in a Function
This example demonstrates a utility function to process arrays differently from other types.
</>
Copy
function processInput(input) {
if (Array.isArray(input)) {
console.log("Input is an array:", input);
} else {
console.log("Input is not an array:", input);
}
}
processInput([10, 20, 30]); // Input is an array
processInput("Hello"); // Input is not an array
Output
Input is an array: [10, 20, 30]
Input is not an array: Hello
The function utilizes Array.isArray()
to distinguish between arrays and other types.