How to detect if a variable is an array

Type checking of objects in JS is done via instanceof, ie

obj instanceof Array

This won’t work if the object is passed across frame boundaries as each frame has its own Array object. You can work around this by checking the internal [[Class]] property of the object. To get it, use Object.prototype.toString() (this is guaranteed to work by ECMA-262):

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

Both methods will only work for actual arrays and not array-like objects like the arguments object or node lists. As all array-like objects must have a numeric length property, I’d check for these like this:

typeof obj !== 'undefined' && obj !== null && typeof obj.length === 'number'

Please note that strings will pass this check, which might lead to problems as IE doesn’t allow access to a string’s characters by index. Therefore, you might want to change typeof obj !== 'undefined' to typeof obj === 'object' to exclude primitives and host objects with types distinct from 'object' alltogether. This will still let string objects pass, which would have to be excluded manually.

In most cases, what you actually want to know is whether you can iterate over the object via numeric indices. Therefore, it might be a good idea to check if the object has a property named 0 instead, which can be done via one of these checks:

typeof obj[0] !== 'undefined' // false negative for `obj[0] = undefined`
obj.hasOwnProperty('0') // exclude array-likes with inherited entries
'0' in Object(obj) // include array-likes with inherited entries

The cast to object is necessary to work correctly for array-like primitives (ie strings).

Here’s the code for robust checks for JS arrays:

function isArray(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
}

and iterable (ie non-empty) array-like objects:

function isNonEmptyArrayLike(obj) {
    try { // don't bother with `typeof` - just access `length` and `catch`
        return obj.length > 0 && '0' in Object(obj);
    }
    catch(e) {
        return false;
    }
}

Leave a Comment