Page 1 of 2
The Associative Array
An associative array is simply a set of key value pairs. The value is stored in association with it key and if you provide the key the array will return the value.
creates an object called array with two keys and two values which in this case happen to be two constant strings.
The key can be either an identifier, a string or a number but more about the difference in the key type as we progress.
You can retrieve a value via it key using array notation:
Which displays the string value2. If you try and access a key that doesn't exist then you get the result undefined.
Notice that there is something slightly odd in this syntax in that when you create the associative array the keys were entered as if they were names (of variables say) rather then strings. However when you access an array the key has to be specified as a string. The reason for this is that the array notation allows you to use an expression as in:
and because of this the key specification has to evaluate to a string.
In short it doesn't matter if you specify the key as an identifier or a string it all works as if you had specified a string. In fact if you want to you can always specify the key as a string e.g.
It helps to think of this in terms of the square brackets  as being the array operator that is
evaluates to the value associated with the key specified by string stored in the associative array object.
You can change the value associated with a key simply by using the array notation to assign the new value, e.g.
You can also add a key/value pair at any time simply by using the array notation to access a key that doesn't exist:
You can also change the value using assignment to a property
and you can add a new key/value pair by assigning to a property that doesn't exist:
Associative arrays as objects
Now the object associated with key2 is a function object and you can retrieve it in the usual way
and if you display the variable method's contents
you will discover that it is the text of the function:
Don't be fooled by this, the method variable doesn't contain a string; it is a function object as you can prove by: