Skip to content

JavaScript object key order

Tangled ropes

Notes:

  • Object keys can either be of type string or symbol.

  • For ordering purposes, a key is considered a number If it can be coerced to a positive integer and when coerced back to a string, it matches the original key. E.g:
    "0" -> 0 -> "0" ("0" is considered a number)
    "00" -> 0 -> "0" ("00" is not considered a number)

The order of object keys is determined as follows.

  1. Numbers are sorted in ascending order.

  2. Strings come after all numbers and respect their insertion order.

  3. Symbols come after all strings and respect their insertion order.

const obj = {
  "z": true,
  [Symbol(10)]: true,
  "a": true,
  2.2: true,
  [Symbol(0)]: true,
  1: true,
  0: true,
};

Reflect.ownKeys(obj);
// ["0", "1", "z", "a", "2.2", Symbol("10"), Symbol("0")]

Reflect.ownKeys is similar to Object.keys but includes Symbol keys as well.