O'Reilly logo

JavaScript: The Good Parts by Douglas Crockford

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Phony Arrays

JavaScript does not have real arrays. That isn't all bad. JavaScript's arrays are really easy to use. There is no need to give them a dimension, and they never generate out-of-bounds errors. But their performance can be considerably worse than real arrays.

The typeof operator does not distinguish between arrays and objects. To determine that a value is an array, you also need to consult its constructor property:

if (Object.prototype.toString.apply(my_value) === '[object Array]'){
   // my_value is truly an array!
}

That test will give a false negative if an array was created in a different frame or window. This test is more reliable when the value might have been created in another frame:

if (my_value && typeof my_value === 'object' &&
        typeof my_value.length === 'number' &&
        !(my_value.propertyIsEnumerable('length')) {
    // my_value is truly an array!
}

The arguments array is not an array; it is an object with a length member. These tests will not identify the arguments array as an array.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required