JavaScript integer associative arrays

04 Oct

I was writing some JavaScript today and I came across some interesting idiomatic quirks with arrays and associative arrays. This is probably well know but I am going to blog about it anyway because it frustrated me for a little while.

I have learned that JavaScript associative arrays are not really arrays at all. I wanted to add an a set of integer keys based on a database unique identifier and post it using AJAX. Now because my key was a high end integer the function was causing my browser to hang!

Why can this be? I have only added one value to the array!

Well it turns out that JavaScript does not create an associative array with integers. Instead it pads the array with undefined for each unused slot up to the value you defined.

The code below it will create an array ten “undefined” elements followed by one element with the value “Ten”. Now imagine using a high end integer of, say 22351550! In addition it does not matter if you use arr[10] or arr["10"] because JavaScript still evaluates the 10 enclosed in a string as an integer.

var arr = [];
arr[10] = "Ten"; // or arr["10"] = "Ten"; 

After a bit of research I found out that keys in JavaScript associative arrays are not actually added array, instead the key is added to the Array object. Therefore in the following scenario the Array object is made up of a 5 element array containing five “undefined” elements and one element with the value “five” and an additional key value pair of “one” => 1.

var arr = [];
arr[5] = "five;
arr["one"] = 1;

document.write(arr.length); //Prints 6
document.write(arr[5]); //Prints five
document.write(arr["one"]); //Prints 1

Now the best way I could find to use integers as an index in an array is not to use arrays at all. Instead use objects like the code below.

var arr = {};
arr[22351550] = "Hello World!";

document.write(arr[22351550]); //Prints Hello World
document.write(arr.length); //Prints undefined

The only issue with this approach is that you will no longer have access to length because Object has no length property.

So basically changing two characters was all that was between success and failure here!

Comments Off

Posted in Uncategorized


Tags: , , ,

Comments are closed.