Out Of Order Keys in ES6 Objects by@jsborked

Out Of Order Keys in ES6 Objects

Just Chris Hacker Noon profile picture

Just Chris

Recently in an article about the joys of JavaScript ES6 Maps, I wrote about the ordering of property keys during their traversal. Expecting keys to be in the same order they were added was a long-time bad assumption to make in JavaScript before ES6.

ES6 introduced property key order, putting into the specification an expectation of how keys will be ordered. Keys are essentially sorted by JavaScript, however, keys still may not always be ordered as you may expect.

I will suggest, that ES6 introduction of this standard may not be a reason to start writing code that is dependent on an expected order. In ES6, of course, maps can be used instead, as a data structure for this purpose.

Basically, this is the problem. You can do this:

x = {zzz:1}
// Object {zzz: 1}
x.a = 2
// Object {zzz: 1, a: 2}
x[window] = 3
// Object {zzz: 1, a: 2, [object Window]: 3}
x['0'] = 4
// Object {0: 4, zzz: 1, a: 2, [object Window]: 3}
// ["0", "zzz", "a", "[object Window]"]

You may not encounter this example in the real world, but you also cannot depend on the keys being listed in the same order they were added, or on a consistent ordering of the keys by the system.

According to the specification, The mechanics and order of enumerating the properties is not specified.

Of course, you can spend time examining the spec, and the different implications of different types of enumeration, or just continue as you may have done in the past, to not create code that depends on the ordering of keys.

It’s not difficult to make some mistakes. Here, we see that we don’t get the order that the keys are entered, the system orders them. Integers, then normal alpha sort, then symbols.

o = {a:0, 2:1, 1:2, b:2, ['zz']:4, window:5}
// Object {1: 2, 2: 1, a: 0, b: 2, zz: 4, window: 5}
// ["1", "2", "a", "b", "zz", "window"]

This is in Chrome 56. As expected the property ordering in ES6, however, these keys are all strings, even though ES6 calls for non-string key types. The keys are strings, ordered — but not — in alpha order. There is a little bit going on here.

So, an option will be to just not make a lot of assumptions about key ordering in Plain old JS objects, and instead, just continue to write code that does not depend on it, or use Maps in ES6, which is nicely suited for this purpose.

Like these articles? Please Recommend Below. Thanks.


Join Hacker Noon

Create your free account to unlock your custom reading experience.