Skip to main content

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; // false

However:

  • If the array was created in another window or frame, the result can be false, because each context has its own Array constructor.
javascript
// Example of the problem: const arr = window.frames[0].Array; arr instanceof Array; // false

3. 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

MethodReturnsReliabilityComment
Array.isArray(value)correct5/5the best option
value instanceof Arraycorrect3/5depends on context
Object.prototype.toString.call(value)correct4/5universal, but bulky
typeof value"object"1/5does not distinguish arrays

Conclusion: Always use Array.isArray(value) - it is the most accurate and shortest way.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.