Associative array versus object in JavaScript

In a JavaScript, an object and array are pretty much the same thing, with an array having a bit of magical functionality (autoupdating the length property and such) and prototype methods suitable for arrays. It is also much easier to construct an object than using an associative array:

var obj = {"my.key": "myValue"};

vs.

var obj = [];
obj["my.key"] = "myValue";

Therefore never use the array object for this, but just the regular object.

Some functionality:

var obj = {}; // Initialized empty object

Delete a key-value pair:

delete obj[key];

Check if a key exists:

key in obj;

Get the key value:

obj[key];

Add a key-value pair:

obj[key] = value;

In JavaScript, objects are associative arrays...there aren't separate concepts for them. You are also able to safely use '.' in a key name, but you can only access the value using the bracket notation:

var foo = {}
foo['bar'] = 'test';
foo['baz.bin'] = 'value';

alert(foo.bar); // Shows 'test'
alert(foo['baz.bin']); // Shows 'value'

If you're using them already and they work, you're safe.

Tags:

Javascript