A JavaScript puzzler

I got this one from Scott, who ran into this problem with his amazing SoundManager library.

The puzzler

What’s wrong with this code:

soundManager.sounds = [];
soundManager.createSound = function(soundID) {
  this.sounds[soundID] = new Sound(...);
}

// (user's stuff):
soundManager.createSound('join');

Try to figure this one out on your own before continuing!!!

The problem

The problem isn’t with the scope of the createSound() function as many people first think, but rather with the associative array sounds and using the key ‘join’.

When you’re saying sounds[‘join’] = ‘foobar’, you’re effectively trying to modify the Array’s built-in join() method. And while not all browsers throw an exception (Firefox 3 doesn’t), it’s bad practice!

The solution

Simply define the sounds variable as sounds = new Object() or sounds = {} when the need for an associative array arises and you’ll be all set. The Array class in JavaScript is an object with extra methods and functionality (like: sort(), join(), etc). Don’t risk of conflicting with those names by using an Array in these situations.

Enjoy quizzing your potential hires during the next interview!

2 Comments

Richard Crowley
about 1 year ago

Using [] as an associative array is usually the sign of someone letting a PHP programmer write JavaScript (tsk tsk). The huge distinction between "array" and "associative array" is one of the reasons I prefer the term "hash" to leave grammatical space between the terms that is proportional to their differences in functionality.

(Please to blog more often, man.)

Mike Malone
about 1 year ago

Ha, yea… like Crowley said, an array isn't appropriate here. The subtleties of javascript are fun.

Re: throwing an exception though, I hope no browsers do. Overriding join with some other object is perfectly legal and shouldn't trigger an exception.

Leave your thoughts

— kept private

— optional

— type in: human