Javascript – Disadvantages to using “associative arrays” in JavaScript

javascript

I'm working with some people are are used to making "associative arrays" in JavaScript like this:

var arr = new Array();
arr.prop_1 = "asdf";

or

arr['prop 2'] = "1234";

It works just like an object because it is. for...in loops can be used and accessing the properties is fine using a dot or a square brace. the lack of native array methods seems not to be lamented. I find it sort of semantically irritating however. Maybe I'm being picky, but I want a good argument for arresting the use of this syntax, but I can't understand how to start. Any suggestions?

Best Answer

Which do you think looks cleaner?

object = new Array();
object.prop1 = 1;
object.prop2 = 2;
object.prop3 = 3;

or

object = {
  prop1: 1,
  prop2: 2,
  prop3: 3
}

?

Also, if you do something like this:

if (object.length === undefined) object.length = 10
object.length // 0

Then object.length will still be 0, which is definitely not what you would expect. You might think this is just a fake example that will never come up in real life, but look at this:

words = 'You should join our club because it is a club'.split(' ')
obj = new Array()
words.forEach(function(x) {
  if (obj[x] === undefined) obj[x] = 0
  obj[x] ++
})
for (var x in obj) console.log(x, obj[x])

This will log:

You 1
should 1
join NaN // <-- oops
our 1
club 2
because 1
it 1
is 1
a 1

Alternatively, you could make an analogy to any other object, like a function:

object = function() {}
object.prop1 = 1;
// ...

Anyone could immediately tell you that that is wrong, and using an array is just as wrong.