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
Selected Reading
How do you check if a variable is an array in JavaScript?
JavaScript provides several methods to check if a variable is an array. The most reliable and recommended approach is Array.isArray(), though instanceof Array also works in most cases.
Using Array.isArray() (Recommended)
The Array.isArray() method is the standard and most reliable way to check if a variable is an array.
<html>
<body>
<script>
var sports = ["tennis", "football", "cricket"];
var name = "John";
var obj = {a: 1, b: 2};
if (Array.isArray(sports)) {
alert('sports is an Array!');
} else {
alert('sports is not an array');
}
if (Array.isArray(name)) {
alert('name is an Array!');
} else {
alert('name is not an array');
}
</script>
</body>
</html>
Using instanceof Array
The instanceof operator checks if an object was created by a specific constructor. It works well in most scenarios.
<html>
<body>
<script>
var sports = ["tennis", "football", "cricket"];
var number = 42;
if (sports instanceof Array) {
alert('sports is an Array!');
} else {
alert('sports is not an array');
}
if (number instanceof Array) {
alert('number is an Array!');
} else {
alert('number is not an array');
}
</script>
</body>
</html>
Why typeof Doesn't Work
The typeof operator returns "object" for arrays, making it unreliable for array detection.
<html>
<body>
<script>
var arr = [1, 2, 3];
var obj = {a: 1, b: 2};
alert("Array typeof: " + typeof arr); // "object"
alert("Object typeof: " + typeof obj); // "object" - same as array
</script>
</body>
</html>
Comparison
| Method | Reliability | Cross-frame Support | Browser Support |
|---|---|---|---|
Array.isArray() |
Excellent | Yes | ES5+ (IE9+) |
instanceof Array |
Good | Limited | All browsers |
typeof |
Poor | N/A | All browsers |
Conclusion
Use Array.isArray() as the standard method for checking arrays in modern JavaScript. It's reliable, handles edge cases, and works across different execution contexts.
Advertisements
