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

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' };

Leave a Comment