Javascript: associative arrays?

Associative arrays are arrays, that are indexed by a string or something like this. Other than an normal array which is indexed by a number only.

For example:

//normal array
array[1] = "value 1"
array[2] = "value 2"
array[3] = "value 3"
 
//associative array
array["val1"] = "value 1"
array["val2"] = "value 2"
array["val3"] = "value 3"

But in Javascript associative arrays don’t exist. Nevertheless I’ve seen it in the whole web, that people use javascript arrays like associative ones. I found even whole tutorials about this topic. Because it seems to work. Why?

An array in javascript is an ordinary object. If you instances one with new or [], you get an array object that behaves like an javascript array. This means, it has methods like “length” or “push” for example. If you log it to the console, the content of the array will listed automatically. But all it’s “array functionality” is working with numbered indexes only!

If you want to have an string as index, you would use following notation:

var array = [];
array["key"] = "value";

What’s happening if you do this? You can add properties to javascript objects in two ways:

//1:
obj.key = "value";
//2:
obj["key"] = "value";

Because an js array is an object (that was build by it’s constructor uses it’s prototype as template), you would add “key” (second method listed above) as property and not as array index! Let’s test this in the firefox console.

//make a new array
var array = [];
 
//list content of it == empty
console.log(array);
> Array [  ]
 
//add new "index"
array["key"] = "value";
 
//list content == empty??
console.log(array);
Array [  ]
 
//show index key == "value"... ok, why is the array empty?
array["key"]
> "value"
 
//show it's length == 0?
console.log(array.length);
> 0

After a click on the logged array, we can examine the whole object:

The resulting discovery is, that “key” is now a property of the array object itself but not an index. So length will be 0 anymore. If you try this to serialize with json for example you will get an empty array as well:

JSON.stringify(array);
> "[]"

Now would the wrong hypothesis of existing associative arrays produce real errors.
How it’s done right? If you want to use something like an associative array, you simply can use objects:

//make an new object
array = {};
 
//set property (or array.key = "value"; would be the same)
array["key"] = "value";
 
//and it's working
JSON.stringify(array);
> "{"key":"value"}"