iteration order for Object

Claus Reinke claus.reinke at
Fri Mar 11 07:07:51 PST 2011

> I believe it is very very important that the ECMAScript standard 
> specify that when a new Object is created, iteration traverses 
> properties in the order they are added, regardless of whether the 
> properties are numeric or not.

Some users might prefer 'in the order of keys'. That is predictable,
and allows for efficient implementation (both sparse and dense).

> A very common use case where order preservation is desirable 
> is providing the set of options for a drop-down list in JavaScript.  
> Essentially all Ajax widget kits have such an API, and usage is 
> generally:
>    selectControl.setOptions({
>       storedValue1 : "displayValue1",
>       storedValue2 : "displayValue2",
>       storedValue3 : "displayValue3"
>    })
> Here are some examples of what alternatives might 
> look like - all of them are far, far worse:

Most of these are just awkward ways of saying "this
is the order I want" and "I also want hashmap access". 
So why not write that out explicitly, with an optional 
ordering parameter, making the enumeration explicit
when the default ordering isn't suitable:

       storedValue1 : "displayValue1",
       storedValue2 : "displayValue2",
       storedValue3 : "displayValue3"

It may seem convenient if keys happen to be enumerated 
in the order they are written, but if that extends to the order 
of insertion, things get complicated (if you delete an entry, 
then reinsert it, has it lost "its" position? do you want an 
"insert before"?).

Ordering by keys would avoid this problem: it wouldn't
matter how or when the entries came to be in the object,
just which keys there are in the object.

Also, there are typically other bits of information you cannot
embed implicitly (keyboard shortcuts, separators, icons,..), so
you will have to switch to an explicit representation anyway,
even if your use case is almost partially covered by one
popular, but not guaranteed, interpretation of the spec!-)

If you're worried about allocation, constant strings can
be commoned up in the implementation. (*)


(*) Is there any overview of the optimizations typically
    done in most major Javascript implementations? 
    I'm not so much asking about "what X does better
    than Y" but about "do I still need to worry about 
    this, or will any decent implementation take care 
    of it?" kind of questions).

More information about the es-discuss mailing list