1

Object keys are not guaranteed to be ordered. Keys can be numerical or strings.

Object.keys(yourObject) returns an array of the keys on that object as strings.

On Chrome, Safari, Firefox, and in node.js if you create numerical keys on an object and return them with Object.keys(), they are all in lexicographical order. As long as the strings are representative of their literal versions (no leading 0's for example) then they are in numerical order.

What I am trying to answer is if Object.keys() guarantees the keys are returned in lexicographical order, or if this is simply an artifact of the defacto implementations in the popular browser/js environments.

1 Answer 1

4

I think the order is implementation-specific. From section 15.2.3.14 of the EcmaScript spec for Object.keys:

If an implementation defines a specific order of enumeration for the for-in statement, that same enumeration order must be used in step 5 of this algorithm.

("this algorithm" refers to the algorithm in the spec for generating the return value for Object.keys.)

And from section 12.6.4 of the spec (on the for-in statement):

The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified.

Note also that lexicographical order is not the same as numerical order. For instance, if the keys are "1", "2", and "10", lexicographical order is "1", "10", "2". (All JS engines that I tested on return numerical order: "1", "2", "10".)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for finding that info. Answers my question, which is that its the defacto implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.