JavaScript Data Structures - The Associative Array
JavaScript Data Structures - The Associative Array
Written by Ian Elliot   
Thursday, 27 October 2016
Article Index
JavaScript Data Structures - The Associative Array
Integer keys

The function evaluation operator

To evaluate a function you use the () operator:

functionobject()

which executes the functionobject to its left and evaluates to the result that the function returns.

For example:

method();

which produces:

 

alert3

 

Notice that you can apply the () operator to a function object no matter how you choose to retrieve it so you can use the property notation to make it look like an object method:

array.key2();

or you can use array notation which makes the method call look very odd:

array['key2']();

It doesn't matter how odd it looks as the () operator always evaluates the function object to its left and returns the result of the function as its value.

So with just a versatile associative array, a function object and the function evaluation operator () JavaScript implements objects. If you reflect on this for a moment you might agree that this is remarkable and elegant.

 

Banner

 

Integer keys

Now we need to look at the special case of integer keys.

As an alternative to string keys you can use integer keys but if you do use a string key you cannot refer to the value using its ordinal position in the array.

For example if you define the array as:

array={'key1': 'value1',
       'key2': 'value2'};

You cannot refer to key1 using array[0] or key2 as array[1]. You can only retrieve values using the key you specified there is no ordinal position in an associative array. 

This might seem obvious but notice that with JavaScript arrays provided by the DOM you can use either the key or the ordinal position. For example

document.forms[1];

or

document.forms['myform'];

both work and return the same object as long as myform is the second form in the array. It is important to notice that this dual indexing doesn't work for general JavaScript associative arrays.

When you use an integer key in an associative array it works just like a string or identifier key - as long as you use array and not property syntax. In fact JavaScript converts the integers to an equivalent string value.

That is if you define:

array={0: 'value1',
       1: 'value2'};

you can retrieve value2 using

array[1]; 

or

array["1"]

but not

array.1;

and not

array."1";

So apart from not being able to use property syntax integer keys are no different. However they look as if they should be different. In particular an associative array with integer keys looks like a standard indexed array - but it isn't.

For example, if we define the array:

array={235: 'value1',
        64:function(){alert("HelloMethod");}};

then you can call the function using:

array[64]();

Only the array elements you define are created in an associative array and so in this case array has just two members - array[235] and array[64].

This is efficient if you only want to use these two elements but JavaScript also provides the Array object which is optimized for storing indexed arrays and has lots of additional methods for working with indexed arrays. As it derives from Object it also can be used as an associative array but in this case the associative storage and the integer storage are handled in different ways.

You can use an Array as an associative array but it really isn't a good idea because you are then incurring an overhead you aren't using and it can become very confusing having and indexed store and an associative store. 

  • If you want to use an indexed array use Array.
  • If you want to use an associative array use an Object.

That is don't use

array=Array();
array["key1"]=value1;

but use

array=Object();
array["key1"]=value1;

This isn't to say that the JavaScript Array isn't useful - it is a very powerful data structure and one we need to take a look at in another data structures chapter.

Object Problems

There is a problem with the fact that the associative array is used as JavaScript's object construct. When you create an associative array you are creating the simplest JavaScript object but this comes with some standard properties. This is mostly fine is you want to use the associative array as an object but not so good if you want to use it as an associative array. What happens is that you get an associative array that already has some key value pairs stored in it.  So for example if you are trying to discover if an associative array is empty you will find that even when you think it should be it isn't. 

This is a particular problem when you want to iterate through the array using a for loop:

for(var key in array) {
 do something with key and array[key]
};

this loops through all of the properties of the object including those that were derived from Object. The usual solution is to use the hasOwnProperty method which returns true if the key is one you actually defined. 

for(var key in array) {
 if(array.hasOwnProperty(key)
    do something with key and array[key]
};

If you are not iterating though an associative array the non-ownProperities are less of a problem and can usually be ignored. 

Since ECMAScript 5 you can create an empty associative array using the syntax:

array=Object.create(null);

In ECMAScript 6 a new associative array object has been introduced called Map.

For example:

array= new Map();

Now array is a Map which is an associative array with no entries. Notice that it does have some built-in properties and methods but these are treated separately from any key value pairs you might add. It isn't exactly the same as an empty object however because you use any object or primitive type as the key in a Map. It also has a size property which returns the number of elements stored in it and a few other useful methods. 

If you can make use of ECMAScript 6 then you should use Map in place of Object when you need an associative array but with care Object does work well. 

 

 datastruct

 

Chapter List 

  1. The Associative Array

  2. JavaScript Data Structures - the Array object

  3. JavaScript Data Structures - the String Object

  4. Speed dating - the art of the JavaScript Date object

  5. A collection object

  6. Javascript data structures - Stacks

  7. JavaScript Data Structures - The Linked List

  8. JavaScript data structures - a Lisp-like list

  9. Stacks, Queue and Deque

  10. Javascript data structures - The Binary Tree

  11. JavaScript Data Structures - Typed Arrays I

  12. JavaScript Data Structures - Typed Arrays II

 

 

To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, FacebookGoogle+ or Linkedin,  or sign up for our weekly newsletter.

Banner
 


jQuery 3 - Working With Data

There are some hidden aspects of using jQuery and its data manipulation functions represent hidden gold. If you have struggled to work with data in JavaScript, and with the DOM in particular, jQuery h [ ... ]



Just JavaScript - In The Beginning Was The Object

JavaScript is a very subtle and sophisticated language and it deserves to be treated in its own right and not as a poor copy of other object-oriented language. In this first chapter of Just JavaScript [ ... ]


Other Articles

 
 
 

blog comments powered by Disqus

<ASIN:0596806752>

<ASIN:0321812182>

<ASIN:1491901888>

<ASIN:144934013X>

<ASIN:193398869X>

<ASIN:1449373216>

 



Last Updated ( Friday, 28 October 2016 )
 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2016 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.