Why Object.keys in JavaScript doesn't always preserve insertion order
Plain JavaScript objects do not always list their keys in the order they were added, because integer-like keys are handled separately. Keys that are non-negative integers below 2^32 - 1 are enumerated first in ascending numeric order, while string keys follow in insertion order. The article shows that adding keys b, 2, a, 1 produces 1, 2, b, a from Object.keys and JSON.stringify. Non-canonical numeric strings such as "01" or "-1" stay in the string group and keep their insertion position. The author recommends using a Map when key order matters, since Map preserves insertion order for every key type.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.

Discussion (0)
Log in to join the discussion and vote.
Log in