JavaScript: Curious order of object properties
1 min read

JavaScript: Curious order of object properties

In JavaScript, Object.keys function returns the keys of a given object.

Object.keys({a: 1, b:2, d: 4, c: 3, }) // prints ['a', 'b', 'd', 'c']

One thing to observe in the above code is that JavaScript preserves the order in which we added the keys. It does not sort the string keys. This order is preserved when we use the parse and stringify functions on JSON also.

So far so good, but JavaScript also supports number as keys. Let us examine how they are ordered.

Object.keys(
   {a: 1, b:2, d: 4, c: 3, 1: '1', 3: 'c', 2: 'b', '4': 'd' }
) // prints ['1', '2', '3', '4', 'a', 'b', 'd', 'c']

When the numbers have involved the order of adding is not preserved, and they are given priority and are sorted in ascending order at first, and then the string keys are placed in the order of addition. Even number strings are treated as number values as you can see in the above example for the key '4'.