Customers’ slips are filed into cabinet o one by one, with number, text and symbol keys: guess the order the engine files the drawers in, then compare a Map…
Why it matters
A subtle bug: an object used as an ordered list with number keys (queue tickets, years, IDs), and the order changes by itself. Knowing the rule, and when to use a Map, prevents a list that jumps around silently.
The key idea
Whole-number keys first, ascending; then text in order of arrival; then symbols
Common mistakes
An object used as an ordered list with number keys, then it jumps around Whole-number keys are sorted ascending quietly. Use a Map or an array of pairs when the order is the data.
Thinking for...in has a different order from Object.keys The same for own keys: this rule holds for every way of reading. (for...in adds inherited keys after them.)
Forgetting number keys become text in an objecto[2] and o['2'] are the same key: both are '2', sorted as a whole number. A Map tells 2 and '2' apart.
Try it in this playground
Watch a number key jump ahead Written later, yet filed ahead of the text keys.
Add a number-like key that does not jump '01', '-1' or '1.5' stay ordinary text.
Write a symbol key first, read with Reflect.ownKeys The symbol still comes last.
Delete a key, then write it again It moves behind the text keys.