Misuse of the Array Object in JavaScript

Thursday, May 18th, 2006 at 19:06 +0000 (UTC) by Alexander Kirk

There is a very good post about Associative Arrays considered harmful by Andrew Dupont.

The title is a bit misleading but correct. When coming accross a piece of JavaScript like this
foo["test"] = 1;
there is nothing wrong about it. It's the basic usage scheme of assoziative arrays. Or should i rather say objects?

While in languages such as PHP arrays used like this $foo = array("test" => 1); is perfectly correct.

In JavaScript
var foo = new Array();
foo["test"] = 1;

works but does not do what you want.

I don't need to repeat Andrew's really great post, but basically you should use Object instead of Array.

var foo = new Object(); // same as var foo = {};
foo["test"] = 1; // same as foo.test = 1;

Now go and read Andrew's post.

via Erik Arvidsson.

btw: that post lead me to Object.prototype is verboten which explains for me why my for (i in myvar) {} loops never worked correctly. I was using prototype.js version < 1.4 (which messed with Object.prototype).

, , , ,

Bookmark on del.icio.us

4 Responses to “Misuse of the Array Object in JavaScript”

  1. Chris Double Says:

    Using 'Object' as an associative array can be bad too:

    http://www.bluishcoder.co.nz/2006/05/associative-arrays-and-javascript.html

    Basically naieve use of Object can return built in operations on Object (like toString).

  2. Thomas Frank Says:

    Object.prototype is erlaubt ;-)
    http://www.thomasfrank.se/object_prototype_is_erlaubt.html

  3. alexander kirk » Blog Archive » JavaScript Tricks And Good Programming Style Says:

    [...] Misuse of the Array Object in JavaScript [...]

  4. Quotes » Blog Archive » Extending prototypes of built-in objects Says:

    [...] This post was in response to a series of posts I’ve seen on blogs lately, such as  Bluish Coder: Associative Arrays and Javascript (Chris Double), JavaScript “Associative Arrays” Considered Harmful (Andrew Dupont), Misuse of the Array Object in JavaScript (Alexander Kirk) and Object.prototype is verboten (Erik Arvidsson). [...]