Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it acceptable style for Node.js libraries to rely on object key order?

Enumerating the keys of javascript objects replays the keys in the order of insertion:

> for (key in {'z':1,'a':1,'b'}) { console.log(key); }
z
a
b

This is not part of the standard, but is widely implemented (as discussed here):

ECMA-262 does not specify enumeration order. The de facto standard is to match insertion order, which V8 also does, but with one exception:

V8 gives no guarantees on the enumeration order for array indices (i.e., a property name that can be parsed as a 32-bit unsigned integer).

Is it acceptable practice to rely on this behavior when constructing Node.js libraries?

like image 899
Aneil Mallavarapu Avatar asked Feb 07 '12 16:02

Aneil Mallavarapu


2 Answers

Absolutely not! It's not a matter of style so much as a matter of correctness.

If you depend on this "de facto" standard your code might fail on an ECMA-262 5th Ed. compliant interpreter because that spec does not specify the enumeration order. Moreover, the V8 engine might change its behavior in the future, say in the interest of performance, e.g.

like image 58
maerics Avatar answered Oct 23 '22 10:10

maerics


Definitely do not rely on the order of the keys. If the standard doesn't specify an order, then implementations are free to do as they please. Hash tables often underlie objects like these, and you have no way of knowing when one might be used. Javascript has many implementations, and they are all competing to be the fastest. Key order will vary between implementations, if not now, then in the future.

like image 41
Ned Batchelder Avatar answered Oct 23 '22 12:10

Ned Batchelder