Reading puzzle outputs
Predicting the output of Object.keys(), for..in, or similar enumeration.
JS Puzzles · Const
JavaScript objects use a special key order: integer property names come first in ascending numeric order, while other string keys follow creation order. Thus, object enumeration is not always simple insertion order.
When JavaScript enumerates an object’s own keys, integer-index-like property names come first in ascending numeric order. Other string keys retain the order in which they were created, so insertion order applies only to that second group.
const object = { 100: "a", 2: "b", 7: "c", apple: 1, banana: 2 };
console.log(Object.keys(object));
// ["2", "7", "100", "apple", "banana"]Integer-index-like keys are listed first in numeric order; other string keys follow their creation order.
Predicting the output of Object.keys(), for..in, or similar enumeration.
Designing serializable records whose displayed keys have predictable ordering.
Choosing between an object and Map when insertion order is a core requirement.
Object keys follow a special order: integer properties are sorted numerically, while other properties appear in creation order. Therefore, adding "2" after "100" can still make it appear first.
Follow-up: How would you preserve straightforward insertion order for arbitrary key types? Use Map, whose entries iterate in insertion order.
For own enumerable string keys, Object.keys() returns keys in the same ordering used by object enumeration. Numeric-looking keys therefore appear in ascending numeric order, followed by ordinary string keys.
Follow-up: What does Object.getOwnPropertyNames() add? It also includes non-enumerable own string properties, while preserving the corresponding enumeration ordering.
The documented object-key rule distinguishes integer properties from other properties. Only the non-integer string-key group follows creation order; symbols are a separate property-key category.
Follow-up: What collection supports keys of any value and insertion-order iteration? Map supports arbitrary key values and remembers insertion order.
Object.keys()Object.getOwnPropertyNames()for..inMapin operator