Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to check whether an array is a true array in JavaScript?
In JavaScript, arrays are actually objects, which makes type checking tricky. When you use the typeof operator on an array, it returns "object" rather than "array", making it unreliable for array detection.
The Problem with typeof
The typeof operator cannot distinguish between arrays and plain objects since both return "object".
Syntax
typeof operand
Parameters: The typeof operator takes an operand and returns a string indicating the data type of the operand.
Example: typeof with Arrays and Objects
<html>
<body>
<script>
var a = [1, 2, 5, "hello"];
document.write("Array type: " + typeof(a));
document.write("<br>");
var b = {};
document.write("Object type: " + typeof(b));
</script>
</body>
</html>
Output
Array type: object Object type: object
Using Array.isArray() (Recommended)
The Array.isArray() method is the most reliable way to check if a value is truly an array. It returns true for arrays and false for all other values.
Syntax
Array.isArray(value)
Parameters: value - The value to be checked.
Return Value: true if the value is an array, false otherwise.
Example: Array.isArray() Method
<html>
<body>
<script>
var a = [1, 2, 5, "hello"];
var res1 = Array.isArray(a);
document.write("Is array: " + res1);
document.write("<br>");
var b = {};
var res2 = Array.isArray(b);
document.write("Is object an array: " + res2);
document.write("<br>");
var c = null;
var res3 = Array.isArray(c);
document.write("Is null an array: " + res3);
</script>
</body>
</html>
Output
Is array: true Is object an array: false Is null an array: false
Comparison of Methods
| Method | Arrays | Objects | Null | Reliability |
|---|---|---|---|---|
typeof |
"object" | "object" | "object" | Not reliable for arrays |
Array.isArray() |
true | false | false | Highly reliable |
Conclusion
Use Array.isArray() as the standard method to check if a value is truly an array. The typeof operator is unreliable for array detection since it returns "object" for both arrays and objects.
