17 Jan 2012
First element of an object in JavaScript
This one will go into the bag of clever hacks which you should use sparingly, if not ever. Given an object like this:
var obj = { a: "foo", b: "bar", c: "baz" }
Here’s how we get the “first” property of the object/dict:
for (var first in obj) break; console.log("First property is: "+first);
We’re assuming here that the enumeration order matches the insertion order. Since ECMAScript standard itself does not specify any enumeration order, most browsers I have tested this in defaults to the insertion order. However, there is a catch: as explained in this discussion, if any of the property names can be parsed as an integer (e.g. 123), then V8 (Chrome’s JS engine) does not give any guarantee on the ordering of the keys.
There is lots of debate on that thread on the merits and demerits of preserving the order of insertion. Although, the V8 guys are pushing back on this on the basis of performance implications, Firefox 7.0 on my mac always preserves the order of insertion.
If you want to try it out on your browser, the following snippet
var a = {"foo":"bar", "3": "3", "2":"2", "1":"1"}; for(var i in a) { console.log(i) };
should print
foo 3 2 1
JavaScript does require the object components have order, just name-value pair, like hash table, is it?
No, ordering requirement is not part of the ECMAScript spec. V8 and major browsers do preserve the order of insertion, except when integers are used when it becomes unpredictable.