Monday, May 22, 2006

Javascript "Associate Arrays" Considered Harmful

This is some consideration you have to take into when using javascript Array type. The sample Array below produce alert boxes: “one”; “two”; “three.”.

var associative_array = new Array();
associative_array["one"] = "Lorem";
associative_array["two"] = "Ipsum";
associative_array["three"] = "dolor";
for (i in associative_array) { alert(i) };

Andrew Dupont has an insightful post warning against the use of the javascript Array type for associated arrays. Instead, use a simple Object would be better. He says,

In JavaScript, one really ought to use Object for a set of key/value pairs. But because Array works as demonstrated above, JavaScript arrays (which are meant to be numeric) are often used to hold key/value pairs. This is bad practice. Object should be used instead.

No comments: