JavaScript doesn’t have associative arrays

Versione italiana

This post is about one common JavaScript misconception: associative arrays.

JavaScript supports associative array syntax, but it doesn’t really have associative arrays. They are useless, because you can use objects.

Let’s create a simple object:

var movie = {
    title : '2001: A space Odissey',
    director : 'Stanley Kubrick',
    year : 1968
};

Here, we define an object variable (movie) with 3 properties (title, director, year). Since properties are always public, we can read them:

alert('Title: ' + movie.title);

Also, JavaScript is very dynamic, so we can also modify or set new properties:

movie.genre = 'sf';

We can also use the classic associative array syntax to access object properties:

alert('Title: ' + movie['title']);

This may seem useless… and in this example, it is. We shouldn’t use that syntax when it is not necessary. But we can use it to access a property that we don’t know a priori:

var prop = 'title';
alert('Title: ' + movie[prop]);

This is particularly useful within for … in loops, which are the JavaScript equivalent of foreach loops:

for (var i in movie) {
    alert(i + ': ' + movie[i]);
}

Enjoy!

Advertisements

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s