Introduction to data structures and algorithms in javascript: Associative Arrays

This is the first of a series of posts that will provide a beginner level introduction to data structures and algorithms in javascript.

A fundamental data structure in javascript is the Associative Array. An Associative Array is an abstract data type that is composed of a collection of key, value pairs such that each key exist only once in the collection.

The reason that an Associative Array is considered to be a fundamental data structure in javascript is that every object in the language is in fact an Associative Array.

Consider the following example:

```javascript
var someArray = new Object();
someArray["A"] = 0;
someArray["B"] = 1;
someArray["C"] = 2;
```

You can get the values stored in the array by referencing the indexes or by object qualified naming:

```javascript
alert(someArray["C"]); // value by index
alert(someArray.C); // value by object qualified naming
```

An Associative Array can also be created using object literal notation:

```javascript
var someArray = {A:0, B:1, C:2};
```

Doing so creates the exact same array as the earlier example.

An important characteristic of the Associative Array in javascript is the fact that it is an object. In other languages, creation of an array requires that you explicitly define the data type. Any addition to the array that is of a different data type would result in an error. In javascript, the array object is defined by its members.

For example, you can add a method to an associative array:

```javascript
var someArray = {A:0, B:1, C:2}
someArray.Count = function() {
return 3;
}
```

This is an important concept for beginners to understand because it may lead to some unexpected behavior. For example, looping through the array will show that there are four elements rather than three.

```javascript
for(ind in someArray) {
alert(ind);
}
```

This problem is typically solved in javascript by creating your own collection object.

```javascript
var Collection = function() {
this.count = 0;
this.collection = {};
}
```

This defines a property for the count and an empty array. To make the collection object useful, it needs methods for adding and deleting elements from the collection array. These methods will update the count property.

```javascript
this.add = function(key, item) {
this.collection[key] = item;
this.count += 1;
}
this.remove = function(key, item) {
this.collection[key] = item;
this.count -= 1;
}
```

The collection object can now be used in the following manner:

```javascript
var someCollection = new Collection();
someCollection.add("A", 0);
someCollection.add("B", 1);
someCollection.add("C", 2);
alert(someCollection.count);
alert(someCollection.collection["A"];
someCollection.remove("C");
```