Arrays and Objects

A while ago I was mentioning how Arrays can be accessed as Objects (since they are Objects). Following on the same thought, here's a curious observation.

Assume we have an array and an object:
var a = [];
var o = {};

We will set a property using named property notation on each of them:
a['test'] = 'hi';
o['test'] = 'hi';

So far, both the array and the object are the same: The array is being used as an Object, thus they will both behave the same. The "test" property will be returned when we use a for in loop.

Things get interesting when we use numbers:
a["5"] = 123;
o["5"] = 123;

Intuition would tell us that since we're using named properties, we should still be using the array as an object, but it turns out that this is not true. What we just did is the same as:
a[5] = 123;
o[5] = 123;

Which results in :
a.toSource() = [undefined undefined undefined undefined undefined 123];
o.toSource() = ({5:123});

Iteration on each of the objects would have to be done in a completely different way, one being a for loop, another being a for in loop, thus demonstrating that care should be exercised when choosing an array or an object for collections.

No comments: