JavaScript, how do I check if this variable is an array

It is common to run functions that return results in JavaScript. With JavaScript being loosely typed, the returned value can be of any data type. In case it is returning an array, there isn't an obvious way to detect it, because arrays are also objects.

The crockford method works but I find it very complicated, here it is:

function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (value instanceof Array) {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}

Now this work perfectly and you can go one with your day. However when I stumbled upon the same problem, I found my own solution before seeing the code above and posted it on stackoverflow.

Array.prototype.isArray = true;

Now whenever I want to check if an object is an array i can do something like this:

var result = doComplexStuffAndReturnResult();

if (result.isArray) {
    // do something
}

Note here if the object is not an array, the property isArray will simply return undefined which is equivalent to false. And just like that, a single line of code solved the problem.


Comments(2)

Kevin :

This blog post came up first in the google search results. But later I found this:

var x = somethingComplicated();
if (Array.isArray(x)) {
   console.log('Yep, it's an array');
}

Ibrahim :

Yep Kevin.

Array.isArray() is now part of JavaScript, and is fairly supported on browsers.

The safe thing to do would be to either use the new method or test if the method exists before overriding it.

Let's hear your thoughts

For my eyes only