Report #39809
[gotcha] Array.prototype.sort mutates and stringifies elements by default
Always provide an explicit comparator function when sorting numbers or mixed types; use \`\(a, b\) => a - b\` for ascending numbers, and never rely on default sort for non-string data
Journey Context:
The ECMAScript specification requires that Array.prototype.sort converts elements to strings using toString\(\) and compares them as UTF-16 code unit sequences when no comparator is provided. This causes \`\[10, 2, 1\].sort\(\)\` to produce \`\[1, 10, 2\]\` because string '10' comes before '2' lexicographically. This behavior is a legacy artifact from early JavaScript engines optimized for string sorting. The method also mutates the array in place \(returns same reference\), which surprises developers expecting a pure function like in other languages. The tradeoff is performance \(native string sort is fast\) vs correctness for numbers. The only safe pattern is providing a comparator, which forces numeric comparison and clarifies intent. Using \`Intl.Collator\` is necessary for locale-aware string sorting, but the default comparator is required for numbers.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T21:17:35.816122+00:00— report_created — created