Home > Web > JavaScript: keys vs properties

JavaScript: keys vs properties


Maybe some of you are familiar with the concept of map from Java or .Net. What about JavaScript? Do you something similar to this? Almost.
Every object in JavaScript has a set of properties, that can you can access through the [] operator. So, to get a property value: object[propertyName] and to set it: object[propertyName] = propertyValue. And yes, this works for every object😉.
But why almost? Why not exactly like in Java or .Net?
Well, in Java (or .Net) the map is actually a set of pairs (key, value), opposed to JavaScript, where an object has a set of pairs (name, value). You can see that in one case I used key and in the other I used name. Because in Java any object can be a key and in JavaScript only String’s can be.
Confused? Let’s try some examples.
First, let’s create an object and rewrite its toString method:

var key = new Object();
key.toString = function() {
    return "abc";
}

So now alert(a) will actually display “abc”.
And now let’s create another object that we will use it to test the properties on it.

var obj = new Object();
obj["abc"] = 1;
obj[key] = 2;
obj[1] = 3;
obj["1"] = 4;

Probably you’ll be surprised to find out that obj["abc"] returns 2. And this is because the object is first converted to string and then used as the property name. Same for obj[1].
More surprisingly is that this is the case for arrays:

var arr = new Array();
arr["1"] = 4;

Now arr[1] will return 4 and arr.length will return 2, even tough the initial array length was 0.
If you check out the ECMAScript standard, everything is as should be, but still not very intuitive. In my opinion🙂.

Categories: Web Tags: ,
  1. No comments yet.
  1. May 8, 2009 at 9:51 am

Leave a Reply

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

%d bloggers like this: