Skip to main content

Checking for an array

1. The modern and reliable approach → Array.isArray()

javascript
Array.isArray(value);

This is the standard ES5 method specifically created for this check. It returns true if the value is an array, and false in all other cases.

Examples for Array.isArray()

javascript
Array.isArray([1, 2, 3]); // true Array.isArray([]); // true Array.isArray('text'); // false Array.isArray({ 0: 'a', 1: 'b', length: 2 }); // false Array.isArray(null); // false

It works correctly even across different contexts (for example, iframe, window, and so on). This makes it the only 100% reliable approach.


2. The old approach → instanceof Array

javascript
value instanceof Array

Example:

javascript
console.log([1, 2, 3] instanceof Array); // true console.log({} instanceof Array); // false

Drawback: if the array was created in a different window or iframe, the check returns false, because it has a different Array constructor.

javascript
// example (pseudocode) iframe.contentWindow.Array !== window.Array;

3. An alternative (manual) → checking via Object.prototype.toString

javascript
Object.prototype.toString.call(value) === '[object Array]'

Example:

javascript
console.log(Object.prototype.toString.call([1, 2, 3])); // "[object Array]" console.log(Object.prototype.toString.call({})); // "[object Object]"

Works correctly, but looks cumbersome: nowadays it is almost always replaced with Array.isArray().


Comparing all the approaches

MethodReturnsProsCons
Array.isArray()true/falseModern, reliableNone
instanceof Arraytrue/falseClear syntaxDoes not work across different contexts
Object.prototype.toString.call()"[object Array]"Always worksVerbose to write

Examples of checking different values

javascript
console.log(Array.isArray([1, 2, 3])); // true console.log(Array.isArray('hello')); // false console.log(Array.isArray({ length: 0 })); // false console.log(Array.isArray(new Array())); // true console.log(Array.isArray(null)); // false

In short

Use Array.isArray(value): it is the most reliable and readable way to check whether a value is an array.

Short Answer

Interview ready
Premium

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