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 do we check if an object is an array in Javascript?
In JavaScript, typeof returns "object" for arrays, which makes it unreliable for array detection. There are three better approaches: Array.isArray(), the constructor property, and instanceof.
The Problem with typeof
typeof returns "object" for arrays, objects, and null − it cannot distinguish arrays from other objects ?
let str = "Abdul Rawoof";
let arr = [1, 3, 5, 8];
let num = 90;
let dict = {a: 1, b: 2};
console.log(typeof str); // "string"
console.log(typeof arr); // "object" ? not "array"
console.log(typeof num); // "number"
console.log(typeof dict); // "object" ? same as array
string object number object
Both the array and the object return "object", so typeof cannot tell them apart.
Using Array.isArray() (Recommended)
Array.isArray() returns true if the input is an array, false otherwise. This is the most reliable method ?
let dict = {name: "John", age: 18};
let arr = ["red", "green", "blue"];
let arr1 = [1, 2, 3, 4, 5];
let str = "hello";
console.log(Array.isArray(dict)); // false
console.log(Array.isArray(arr)); // true
console.log(Array.isArray(arr1)); // true
console.log(Array.isArray(str)); // false
console.log(Array.isArray(null)); // false
console.log(Array.isArray(undefined)); // false
false true true false false false
Using the Constructor Property
Check if the constructor property equals Array. This works for most cases but fails on null and undefined ?
console.log("".constructor === Array); // false
console.log({}.constructor === Array); // false
console.log([].constructor === Array); // true
console.log([1, "hello"].constructor === Array); // true
console.log(new Array().constructor === Array); // true
// These would throw TypeError:
// null.constructor === Array
// undefined.constructor === Array
false false true true true
Using instanceof
The instanceof operator checks if an object is an instance of the Array constructor ?
console.log([1, 2, 3] instanceof Array); // true
console.log({a: 1} instanceof Array); // false
console.log("hello" instanceof Array); // false
true false false
Comparison
| Method | Syntax | Handles null/undefined? | Reliable? |
|---|---|---|---|
typeof |
typeof x === "array" |
Yes | No − returns "object" for arrays |
Array.isArray() |
Array.isArray(x) |
Yes (returns false) | Yes − recommended |
.constructor |
x.constructor === Array |
No (throws TypeError) | Mostly |
instanceof |
x instanceof Array |
Yes (returns false) | Fails across iframes |
Conclusion
Use Array.isArray() as the standard way to check if a value is an array in JavaScript. It handles all edge cases including null, undefined, and cross-frame objects. Avoid relying on typeof since it returns "object" for both arrays and plain objects.
