Home / Assigning values to associative arrays in Javascript

Assigning values to associative arrays in Javascript

Javascript has zero indexed integer arrays and also associative arrays. They work in a similar manner but there is a useful way to be able to initialise an associative array with both keys and values in one call. This post will look at the way a zero based integer based array can be initialised and then the ways it can be done with associative arrays in Javascript.

A zero based integer keyed Javascript array can be initalised with values like so:

var items = new Array(
  123456, 
  789012,
  345678,
  901234
);

The following code is used to loop through the above Javascript array and output all the values:

for(index = 0; index < items.length; index++) {
  document.write( index + " : " + items[index] + "<br />");
}

And this is the result of the above code:

0 : 123456
1 : 789012
2 : 345678
3 : 901234

Easy stuff. But how do we do the same for an associative array? The most obvious way is to first initalise the array and then add values to it assigning values to both the array key and value like so:

var items = new Array();
items['foo'] = 123456;
items['bar'] = 789012;
items['baz'] = 345678;
items['bat'] = 901234;

And then loop through the array:

for(var index in items) {
  document.write( index + " : " + items[index] + "<br />");
}

to produce the following output:

foo : 123456
bar : 789012
baz : 345678
bat : 901234

OK, so that’s good, but it’s not terribly efficient, and there’s a much easier way to intialise the associative array with values in Javascript which is more like the zero based array in the first example. The example below shows an easier way to do it that requires only one line of code (OK, I’ve split it onto multiple lines for readability, but it’s still only one command), and will display the same output as the example directly above:

var items = {
  "foo" : 123456,
  "bar" : 789012,
  "baz" : 345678,
  "bat" : 901234
};

Much easier, don’t you think?

Examples that don’t work

Using the second associative array example with only values doesn’t work:

var items = {
  123456, 
  789012,
  345678,
  901234
};

But it would work if you did this:

var items = {
  0 : 123456, 
  1 : 789012,
  2 : 345678,
  3 : 901234
};

or this:

var items = {
  10 : 123456, 
  25 : 789012,
  19 : 345678,
  57 : 901234
};

Using "new Array()" with values, using colons as in the { } syntax, doesn’t work:

var items = new Array(
  'foo' : 123456, 
  'bar' : 789012,
  'baz' : 345678,
  'bat' : 901234
);

and nor does it using PHP style coding:

var items = new Array(
  'foo' => 123456, 
  'bar' => 789012,
  'baz' => 345678,
  'bat' => 901234
);