JavaScript

Checking if variable is an Array

Since the last time I tackled this issue, there has been some improvements to newer versions of JavaScript. The Array object now has the isArray() method. To check if an object is an array, all you have to do is pass it as a parameter and a boolean as a result.

var obj1 = [1,2,3],
    obj2 = {a:1,b:2,c:3};

Array.isArray(obj1); // true
Array.isArray(obj2); // false

This would be great if it worked on all browsers. My solution to handle older browser is to add isArray to the Array prototype manually.

Array.prototype.isArray = true;

Now all we have to do is to check if the object has the isArray property and we are set.

Array.prototype.isArray = true;
var obj1 = [1,2,3],
    obj2 = {a:1,b:2,c:3};

obj1.isArray; // true;
obj2.isArray; // undefined 

You can use this in a condition to test if the variable is an array.

If you want to implement it the same way as the Array.isArray() works, you can use the Crockford method and just test if the browser supports the property first.

if (!Array.isArray) {
    Array.isArray = function (value) {
        return value instanceof Array;
    };
}

And there you have it, now you have 2 ways to determine if a variable is an array. The first one is by adding a isArray property to the Array prototype and setting it to true. The second one is to check if the browser supports .isArray() method. If not, add it to the array object using the example above.

Do you have a better method? Don't forget to share it with us.


Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only