Why does a string index in an array not increase the 'length'?

Because the length is defined to be one plus the largest numeric index in the array.

var xs = [];
xs[10] = 17;
console.log( xs.length ); //11

For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.


Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:

array.a = 'foo';
array['a'] = 'foo';

Those properties are not part of the "data storage" of the array.

If you want "associative arrays", you need to use an object:

var obj = {};
obj['a'] = 'foo';

Maybe the simplest visualization is using the literal notation instead of new Array:

// numerically indexed Array
var array = ['foo', 'bar', 'baz'];

// associative Object
var dict = { foo : 42, bar : 'baz' };

Tags:

Javascript