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
trueif the value is an array, andfalsein 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); // falseIt 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 ArrayExample:
javascript
console.log([1, 2, 3] instanceof Array); // true
console.log({} instanceof Array); // falseDrawback: if the array was created in a different window or iframe, the check returns
false, because it has a differentArrayconstructor.
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
| Method | Returns | Pros | Cons |
|---|---|---|---|
Array.isArray() | true/false | Modern, reliable | None |
instanceof Array | true/false | Clear syntax | Does not work across different contexts |
Object.prototype.toString.call() | "[object Array]" | Always works | Verbose 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)); // falseIn short
Use
Array.isArray(value): it is the most reliable and readable way to check whether a value is an array.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.