Thursday, November 19, 2009

Testing if an element is an array, in Javascript

Up till now, I have always used this function (taken from Crockford's The Good Parts) to check for array validity in JavaScript:

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

But recently I came to know that a guy from Google (Mark Miller) used the following condition (by carefully reading the ECMAScript Standard):

var is_array = function (value) {
    return Object.prototype.toString.call(value) === '[object Array]';
};

Although mind you, the above isn't perfect either, because it can easily be broken by extending the Object prototype :

// native prototype overloaded, some js libraries extends them
Object.prototype.toString= function(){
  return  '[object Array]';
}

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

var a = {};
alert(isArray(a)); // returns true, expecting false;

But everyone should keep in mind that extending the Object prototype in JavaScript is a big NO-NO . So, as of the moment, the most robust and concise way you can use to check for array validity in JavaScript is by using Miller's method.

1 comment:

Post a Comment