Array check
1. Array.isArray(value) - the modern and reliable way
javascript
Array.isArray([1, 2, 3]); // true
Array.isArray("text"); // false
Array.isArray({}); // false- Works in all modern browsers and Node.js.
- Correctly identifies arrays even from other contexts (for example, from an iframe).
- This is the recommended way to check.
2. instanceof Array - old, but functional
javascript
[1, 2, 3] instanceof Array; // true
"abc" instanceof Array; // falseHowever:
- If the array was created in another window or frame, the result can be false, because each context has its own
Arrayconstructor.
javascript
// Example of the problem:
const arr = window.frames[0].Array;
arr instanceof Array; // false3. Checking via Object.prototype.toString.call()
This method is universal for any type (often used in libraries).
javascript
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call("hi"); // "[object String]"4. Why not typeof
javascript
typeof []; // "object"typeof does not work because an array is an object, and the result is always "object".
Summary
| Method | Returns | Reliability | Comment |
|---|---|---|---|
Array.isArray(value) | correct | 5/5 | the best option |
value instanceof Array | correct | 3/5 | depends on context |
Object.prototype.toString.call(value) | correct | 4/5 | universal, but bulky |
typeof value | "object" | 1/5 | does not distinguish arrays |
Conclusion: Always use
Array.isArray(value)- it is the most accurate and shortest way.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.