AceDevHub
Advanced JavaScript Interview QuestionsAdvancedConcept

JavaScript · Question 76

What ordering rules should you know when JavaScript enumerates an object’s own property keys?

Direct answer

For ordinary own-key ordering, array-index-like string keys are ordered numerically first, other string keys follow creation order, and Symbol keys follow creation order after the string keys; individual APIs can additionally filter which keys they return.

A common misconception is that object properties are either completely unordered or always simple insertion order. Modern JavaScript defines useful ordering rules for ordinary objects. Keys that are canonical array-index-like strings are handled before other strings, and those numeric-looking keys are ordered numerically rather than purely by insertion time.

For an object created as const x = { b: 1, 10: 2, 2: 3, a: 4 };, APIs that expose ordinary own string-key order will place "2" before "10", followed by non-index strings such as "b" and "a" in their creation order. Symbols form a later category in own-key order.

  • Object.keys() filters to enumerable own string keys.
  • Object.getOwnPropertyNames() includes non-enumerable own string keys.
  • Reflect.ownKeys() includes own string and Symbol keys.