user3882106 user3882106 - 2 months ago 10
Javascript Question

Why can't you access this array with index?

Why does this array have a

length
property of 0? And as a follow up to that question, why can't you access an item in this array with an index value?

Consider the following:

var box = [];

box['material'] = 'cardboard';
box['size'] = 'small';

box.length; //0
console.log(box);
//[ material: 'cardboard', size: 'small' ]

box[0]; //undefined


However, when I do the following:

var box = [];
box['0'] = true;
box['1'] = 'cardboard';
box['2'] = 'some value';

box.length; //3
box[0];// true


Why does it output the correct length in this case, since '0' is a string and not a number and access the correct item with the 0 index?

Answer

In JavaScript, the length of an array is always one more than the largest numeric (integer) property name. Arrays can have properties whose names are not numeric, but they don't count towards the length of the array (and they are ignored in some other important situations).

Object property names are always strings, but strings that are non-negative integer values when interpreted as numbers are special in arrays. Accessing properties with numeric values works because the numbers are first converted to strings; thus box[0] and box['0'] do exactly the same thing.

Comments