LAST UPDATED: AUGUST 4, 2021
How to Check If Object is an Array in JavaScript?
Answer: Using isArray()
method
JavaScript offers a pre-defined method Array.isArray()
method, which allows us to check whether the given object is an array or not.
The Array.isArray()
method returns true if the object is an array and if not, then it returns false.
Example: Using isArray()
method
In the given example, we have created one array and one object. Then using isArray()
function we have checked whether the object is an array or not.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Checking whether the object is an array or not</title>
</head>
<body>
<script>
var var1 = {name: "Harry", age: 26};
console.log(typeof(var1));
console.log(Array.isArray(var1));
var var2 = ["HTML", "CSS", "Bootstrap 4", "javaScript"];
console.log(typeof(var2));
console.log(Array.isArray(var2));
</script>
</body>
</html>
Output
Example: Using constructor
In the given example, we have checked whether the given object is an array or not using the constructor.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Checking whether the object is an array or not</title>
</head>
<body>
<script>
var progLang = ["Java", "C", "C++"];
if(progLang.constructor === Array){
console.log('Variable "progLang" is an array.');
}else{
console.log('Variable "progLang" is not an array.');
}
</script>
</body>
</html>
Output
Conclusion
In this lesson, we have discussed how to check whether the given object is an array or not. JavaScript offers a pre-defined function named Array.isArray()
. This function checks whether the object is an array or not. We just have to pass the variable within the parentheses of this function. This function returns true if the object is an array. Otherwise, it returns false.