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

There are no comments added yet.

Let's hear your thoughts

For my eyes only