Associative Arrays

All the arrays we've seen so far have stored values according to their numerical position in the array. An associative array uses strings instead of numbers to store values. For example, the following lines create a phone book with an associative array:

var phone_book = new Array();
phone_book["dave thau"] = "(415) 555-5555";
phone_book["information"] = "(415) 555-1212";

The first line creates a new, empty array, as we've seen before. The next two lines put two associations into the array. The first associates the string dave thau with another string, (415) 555-5555. The second associates the string information with the number to dial for Information. To retrieve that number, you would look it up using a line like this:

var information_number ...

Get The Book of JavaScript, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.