JavaScript Data Structures - The Associative Array
Written by Ian Elliot   
Thursday, 01 December 2022
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

 


JavaScript Data Structures 

Cover

Contents

  1. The Associative Array
  2. The String Object
  3. The Array object
  4. Speed dating - the art of the JavaScript Date object
  5. Doing JavaScript Date Calculations
  6. A Time Interval Object
  7. Collection Object
  8. Stacks, Queue & Deque
  9. The Linked List
  10. A Lisp-like list
  11. The Binary Tree
  12. Bit manipulation
  13. Typed Arrays I
  14. Typed Arrays II
  15. Master JavaScript Regular Expressions
    * First Draft

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

Banner
 


JavaScript Jems - The Inheritance Tax

JavaScript should not be judged as if it was a poor version of the other popular languages - it isn't a Java or a C++ clone. It does things its own way.  In particular, it doesn't do inheritance  [ ... ]



JavaScript Jems - Objects Are Anonymous Singletons

JavaScript should not be judged as if it was a poor version of the other popular languages - it isn't a Java or a C++ clone. It does things its own way.  In particular, every object can be regard [ ... ]


Other Articles

raspberry pi books

 

Comments




or email your comment to: comments@i-programmer.info

<ASIN:1871962579>

<ASIN:1871962560>

<ASIN:0596806752>

<ASIN:0321812182>

<ASIN:1871962501>

<ASIN:1871962528>

 



Last Updated ( Thursday, 01 December 2022 )