Wrong

I stumbled across this widely linked post about arrays in javascript. The author, who I believe is generally well respected in the webdev world, goes on about how you shouldn’t use arrays in JS as hash tables, because an array in JS is just an extension of object. Now, clearly, the Array() constructor is generally to be avoided for the reasons noted in the article.

However, if you use var myHash = [] in any world other than prototype, you will be able to happily use it as a hash table, because it is an object and in javascript objects ARE hash tables. So sure, creating a var as an array doesn’t strictly mean anything if you are using it as a hash table, but I think it is actually good practice, because when a developer sees a variable declared as [] they generally expect it to be an array or a hash of key=>value pairs. I just don’t really see the problem here.

Maybe on his team the author would rather use object literals for hash tables. Fine, but that doesn’t make it harmful to declare an object as an array and populate it as a hash. Further, in the comments several people seem to complain about for…in, which is totally insane because it is the only form of object reflection available in javascript! Its completely essential. I suppose people just need to be careful about “considered harmful” articles, because in a flexible, dynamic language you can do whatever you want. Some things might be slower, something might be worse practice in most cases, but its a flexible language, use it how you like.

Leave a Reply