Loupax
Loupax

Reputation: 4934

How do associative arrays work in JavaScript?

I know how to use them, but I wonder how they work under the hood, and how slow they are compared to regular arrays.

My guess is that this:

myArray['value'] = 10;
myArray['another_key'] = 11;

is translated to something like this:

myArray[0][0] = 'value';
myArray[0][1] = 10;
myArray[1][0] = 'another_key';
myArray[1][1] = 11;

[EDIT]

Looks like my guess was wrong, and that the keys of the array are actually properties of an object. So, to collect all the answers I got in one place:

Upvotes: 0

Views: 529

Answers (3)

Felix Kling
Felix Kling

Reputation: 816970

It is totally different.

First, never use arrays as associative arrays. Arrays only work properly with numerical indicies. For example:

var a = [];
a['foo'] = 'bar';
console.log(a.length) // prints 0

Not even objects are really appropriate for associative arrays if you think that its elements should maintain a certain order (e.g. like in PHP). That is not the case. But objects are good for hash tables, which is sufficient in most cases.

Internally, arrays are only objects as well. So when you have an array:

var a = [];
a[0] = 42;

then 0 is actually converted to a string and added as property to the object (note the last line (__proto__: Object)):

enter image description here

You can access that property with a['0'] as well.

Of course it could be that these operations are optimized internally for arrays, but that depends on the engine.

So in the end, a[0] = 42; or o['value'] = 42; (with o = {}) produce the same results

enter image description here

and accessing them with either a[0], o['value'] or o.value is the same as well.

Upvotes: 5

Guffa
Guffa

Reputation: 700690

An associative array is just an object. Setting items is just setting properties, so your code is the same as:

myArray.value = 10;
myArray.another_key = 11;

Looking up properties in an object is pretty fast, so you shouldn't normally have any performance problems with that.

Upvotes: 2

dotancohen
dotancohen

Reputation: 31511

Javascript does not have associative arrays. You can use objects instead. http://www.quirksmode.org/js/associative.html

Upvotes: 0

Related Questions