I have this test:
let obj = {
"5555555555": 5,
"4444444444": 4,
"3333333333": 3,
"2222222222": 2,
};
console.log(Object.keys(obj));
The output is ["2222222222", "3333333333", "5555555555", "4444444444"]
However, the EcmaScript 2015 specification defines the order for [[OwnPropertyKeys]]:
- For each own property key P of O that is an integer index, in ascending numeric index order,
a. Add P as the last element of keys.
And integer index is defined as:
An integer index is a String-valued property key that is a canonical numeric String and whose numeric value is either
+0
or a positive integer ≤ 253−1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 232−1.
As all four properties in obj
, in the snippet above, are integer indexes by definition, how come they are not listed in numerical order when I call Object.keys
?
I see this same order in Chrome, Firefox, Edge, even Internet Explorer 11. It seems like they apply the "ascending numeric index order" for array indexes, not (all) integer indexes. Only that can explain why 1111111111 and 2222222222 are ordered first and in numerical order (the only two keys that are < 232-1), and 4444444444 and 5555555555 are ordered last in their original relative order.
What am I missing? Are these implementations violating the specs?
None of the major implementations had ever been in line with that particular ES6 specification. But note that exceptions were allowed in EcmaScript 2015-2019 (see this)
Concerning the described behaviour, see for instance the V8 bug report Issue 7874: Respect OrdinaryOwnPropertyKeys order.
While EcmaScript 2016, 2017 and 2018 specifications remained unchanged in this respect, it was decided to align EcmaScript2019 with reality. The section on [[OwnPropertyKeys]]() now reads:
- For each own property key P of O that is an array index, in ascending numeric index order, do
a. Add P as the last element of keys.
So reference is to array index, which has an unchanged definition (+0 ≤ i < 232−1).
This change occurred in pull request Normative: Use array indices instead of integer indices in OrdinaryOwnPropertyKeys. See also the comments and cross-references there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With