jump to navigation

JavaScript Associative Arrays Demystified July 10, 2008

Posted by xk0der in : Programming , trackback

Javascript hides a lot of arsenal beneath its simplicity. In this post I’ve tried to explain normal javascript arrays and associative arrays starting with absolute basics and then presenting the advance concepts that are often overlooked but are simple to understand and are very handy. I’m not a Javascript guru :) . This post is more about what I’ve discovered overtime while coding in Javascript. Hope it helps and saves your time.

Please Note: A single line in the code snippet may wrap or may have been split to fit it into the blog’s page layout. All code snippets are provided for illustration purpose. Though they should work (execute) fine without any modification, I’ve not tested all the snippets presented here.

Normal indexed arrays

I’ll start the discussion with normal indexed arrays. Most of the text in this section would be known to many, but might be useful for Javascript newbies.

In Javascript you can create and use normal arrays as follows:

var myArray = new Array();

Normal arrays uses positive integers numbers (including zero) as index. To store elements to this array. you can use the following syntax.

myArray[0] = 200;
myArray[1] = 300;

Where 200 and 300 are the values stored at the first and the second location in the array, respectively ( index 0 is the first location).

Another way to assign elements is to use the array constructor as follows.

var myArray = new Array(200, 300);

The above code has the same effect as the previous one, storing 200 at the first location (index 0) and 300 at the second location (index 1)

Tip 1 : The array.length property
If you want to add an element at the end of a normal, number indexed array (the one we used above). use the following code.

myArray[myArray.length] = someValue;

For example:

var myArray = new Array();

myArray[myArray.length] = 200;
myArray[myArray.length] = 300;

For the first assignment, myArray.length would be 0, so 200 is stored at the first location (index 0). after the assignment the array length becomes 1 hence 300 is stored at the second location (index 1). At the end if you try to check the length property of myArray, it will contain the value 2. As you would have guessed, you can always find the number of elements in an array by using it length property, as follows

arrayObject.length

Tip 2 : Quick array creation.
You can use the square bracket operator to quickly create an array. This is specially useful when you need to pass array arguments to functions. An example follows.

var myArray = [200, 300];

alert(myArray); // outputs: 200,300
alert(myArray.length); // outputs: 2

The first line in the code, is equivalen to:

var myArray = new Array(200, 300);

Here’s how you can use this trick while passing argument to functions:

function sumAll( arrayArg )
{
    var sum = 0;
    for ( i = 0 ; i < arrayArg.length; i++)
    {
        sum = sum + arrayArg[i];
    }
     alert("Sum is:" + sum);
}

sumAll([100,200,300,400]);
// the alert in sumAll() function should
// display - Sum is: 1000

Tip 3 : Javascript array elements can be heterogeneous
I’m only storing numbers in all the above examples but Javascript arrays can store a string, an object and for that matter another array itself (as an array is nothing but an object). And one important thing to remember is that unlike many other programming language, all elements need not be of the same type. You can store numbers and strings in an array at the same time as illustrated below.

var mixArray = new Array();

mixArray[0] = "Hello World";
mixArray[1] = 100;

var anotherMixArray = new Array(200,
                                300,
                                "Hello Again",
                                500);

var moreMixArray = new Array();

moreMixArray[0] = 600;
moreMixArray[1] = mixArray;

moreMixArray[2] = new Array(700,
                            anotherMixArray);

moreMixArray[3] = "Incredible!";

The above code may look like madness at first glance, but is perfectly valid and provides a great bit of flexibility to the programmer. if you cannot figure out what’s going in that piece of code, draw it out and things will make sense, look at the figure below. :)

Array Madness Explained

Sparsely populated Array

In Javascript arrays can be sparsely populated, that is, you need not fill-up each and every location in an array. Consider the following example.

var myArray = new Array();

myArray[0] = 200;
myArray[5] = 300;

alert(myArray);

// the alert dialog box shows 200.
alert(myArray[0]);

// 300 will be shown in the alert box.
alert(myArray[5]);

// this shows 'undefined'
alert(myArray[2]);

// this will show '6' in the alert box.
alert(myArray.length);

The above code creates a sparsely populated array, courtesy the statement myArray[5] = 300; All intermediate locations from index 1 to index 2 are created but nothing is stored there, essentially they are not-defined. Note that though the number of elements stored is two the array length is shown as 6. This is because, though the elements may be empty (technically undefined) they are part of the array.

An examples that uses the techniques shown above.

// Store Fibonacci series in an array

// Disclaimer: the code snippet here
// just serves the purpose of
// illustrating usage of array and by
// no means is an efficient or
// elegant solution (even if it is one

;)

 )
// to calculate or find Fibonacci series/numbers.

var myArray = new Array;
var maxNum = 100;

var a = 0;
var b = 0;
var c = 1;

while(c < maxNum)
{
    myArray[myArray.length] = c;
    a = b;
    b = c;
    c = a + b;
}

// displays
// Fibonacci Series : 1,1,2,3,5,8,13,21,34,55,89
alert("Fibonacci Series :" +  myArray);

// display - Array Length : 11
alert("Array Length :" + myArray.length);

Associative Arrays or something else!

Before we explain the “something else!” part in the heading, some definitions and examples.

Associative Array: In simple words associative arrays use Strings instead of Integer numbers as index. So we can have something like,

var myArray = new Array();

myArray["abc"] = 200;
myArray["xyz"] = 300;

Here the indexes “abc” and “xyz” are called keys and these keys are mapped to the values 200 and 300. So we say that the key “abc” maps to ‘200′ and similarly the key “xyz” maps to ‘200′. It’s that simple!

Where to use associative arrays?
I’m presenting few example here, where associative arrays may be helpful.

Databases: Consider a table with following columns and types, in the format COLUMN_NAME as TYPE

NAME as TEXT, MARKS as NUMBER, DOB as DATE.

In your code if you were to find the type of a column, you can create an associative array as follows:

var studentTypes = new Array();

studentTypes["NAME"] = "TEXT";
studentTypes["MARKS"] = "NUMBER";
studentTypes["DOB"] = "DATE";

alert("Type of MARKS is :" +
      studentTypes["MARKS"] );

As with normal arrays we need not remember the index number. Using the column names as keys we can directly get the types from the mapping.

This is a very trivial example, but the associative array concept can greatly simply coding for similar scenarios.

“But what about the ’something else!’ part”, I hear you saying :) read ahead to know the truth about Javascript associative arrays.

Magic and mystery continued…

Try the following code snippet.

var myArray = new Array();

myArray["a"] = 100;
myArray["c"] = 200;

// the alert box will contain nothing,
// it'll be empty!!
alert(myArray);

“What happened here? why did the alert box print nothing? why didn’t it output 100,200?”, don’t be too startled, more mysterious things are about to happen…

Try another piece of code.

var myArray = new Array();

myArray["a"] = 100;
myArray["c"] = 200;

alert(myArray.length); // output: 0

“What? ZERO!” … yes zero, because my friend there is NO such things as associative arrays in Javascript. “WHAT!”, you say, but you read it correct. Read ahead to know what these “key” to “value” mappings are.

Object and Properties and Not Associative Arrays

Javascript allows you to add properties to objects by using the following syntax:

Object.yourProperty = value;

An alternate syntax for the same is:

Object["yourProperty"] = value;

Shoosh!… If you are not getting what’s going on, you may skip to the next section, and I promise, it won’t hurt your usage of the so called associative arrays in Javascript.

Well, back to the discussion. In the code where we say myArray["a"] = 100; What we really are doing is creating a property named “a” for the “myArray” object and storing the value 100 in the property.

try the following code, to make things clearer,

var myArray = new Array();

myArray["a"] = 100;

myArray.b = 200;

alert(myArray.a);
alert(myArray["b"]);

Remember: These are not alternate ways to assign values to an associative arrays, these are alternate ways to assign properties to an object.

The object “myArray” is of the type Array() in our example, courtesy the statement “var myArray = new Array();”. But in theory and in practice you can use any Class’s object to simulate the associative array. Try the following code and you’ll get what I mean by using any Class’s object.

var myArray = new Date();

myArray["a"] = 100;
myArray["b"] = 200;

alert(myArray["b"]); // output: 200.

Got the point? Good! :), but I suggest you use the Array class (for simulating the associative array behavior), as it makes the code more obvious (when read). As pointed by Nelson, using an Array class comes with extra baggage, like the functions push(), pop() and sort() and the property .length, which are of no use with the data we are storing. So as suggested by Nelson, we can use the plain Object class or the curly bracket notation to simulate the associative array behavior.

Now that the mystery is solved, just to avoid confusion, let’s use the term “associative arrays” for the Object-Property assignment behavior.

Tip 4 – Quick associative array creation

We cannot use the Array() constructor to assign elements to associative arrays as we did with normal (proper) arrays. But we can use the Javascript’s object notation to simulate the square bracket effect. (see tip 2).

Check out the code first:

var myArray = { "abc":200, "xyz": 300};

alert(myArray["abc"]); // output: 200

The curly braces is a quick way to define an object, specifically and unnamed object or an object with no class. Normally we have been creating objects using the new operator, which expects a class name to be present.

The colon separates the property name and the value associated with it. The property name goes to the left of the colon and the value goes to the right. Multiple properties are separated using a comma.

The quotation marks enclosing the property names is optional, but is required if you are going to use property names with spaces.

In the associative array terminology, just replace the term property from the above paragraph with key.

Tip 5 – using for(in) to iterate through an Associative array

You can iterate through an associative array using the for..in loop construct as follows.

var myArray = {abc: 200, "x y z": 300};

for(key in myArray)
{
   alert("key " + key
         + " has value "
         + myArray[key]);
}

The above code snippet will display two alert boxes with the following text “key abc has value 200″ and “key x y z has value 300″ respectively.

Some explanation:
The for loop here iterates through all the properties of the object “myArray”. The variable “key” will contain the property name inside the for block, which can be used with the object to retrieve the property’s value.

In terms of associative array, you can think of the for..in construct to be iterating through all the “keys” in the array one by one, assigning the key’s name to the variable “key”.

Epilogue

I’ve not gone into much details about the Javascript object notation and neither have I dealt too extensively with the associative array concept, but nevertheless I’ve tried to present the concept of associative arrays in as simple a manner possible. I hope the post will help the newcomers to Javascript and experienced programmers alike.

Thank you for reading. :)

Like this post?
  • http://santmedia.co.uk Steve Sant

    Great! I’ve been looking for an explanation of the curly bracket, and colon type notation of nested associative arrays for hours! Your site was the first I found with anything my poor brain could absorb! Thanks!

  • http://www.fuzzystyle.com Fuzzystyle

    Thank you for the article, you clarified a few points for me.

  • Noah

    Nice article. Thanks!

  • http://alekdavis.blogspot.com Alek Davis

    Good explanation. Thank you.

  • http://www.somebits.com/weblog/ Nelson

    This is a great explanation and I’m seeing it pointed to a lot (like on StackOverflow). Thanks!

    I’m new to Javascript, but I have opinions :-) I think “I suggest you use the Array class (for simulating the associative array behavior)” may be bad advice. The problem is that your associative array thingie will have a bunch of properties like .length and functions like push() and sort() that don’t work on the data you’re actually storing there. A lot of the Javascript code I’m reading uses a plain Object instead, it seems clearer that way.

  • http://xkoder.com xk0der

    @Nelson:
    You have a valid point, I just didn’t think about it, while writing. :)

    I’ll correct the post.

    Thanks for pointing out this issue :)

  • Hans Schou

    As Steve, I was also looking for that curly bracket colon notation.

    Thanks.

  • http://www.commacommacrash.com Joel Bradshaw

    Awesome post! I’ve never quite understood how all this works, and this post cleared it right up. Thanks much!

  • http://lesliesblog.smartsnight.com/ seedogiag

    Great, I didn’t heard about that until now. Thx!!

  • Ulrich

    I would use new Object() instead of new Array() for creation, because there are no real associative _arrays_ in JS.

  • http://xkoder.com xk0der

    @Ulrich wrote “there are no real associative _arrays_ in JS”

    That’s the whole point of this blog post :), to clarify and put forth the point that “there are no associative arrays in JavaScript” instead they are properties of an Object.

    Use of Array() in the initial examples is make it easier for the reader to understand the concept.

    If you read the two paragraph above sub heading “Tip-4″ it mentions what you state in your comment. :)

  • Pingback: Review and Geolocation | IDIA 619: Interactive Multimedia

  • Pingback: Codecademy CodeYear Lesson 10 – Arrays and Rock, Paper, Scissors « The Man from the Ministry

  • Pingback: Associative Arrays in JavaScript | Kevin Chisholm - Blog