Report #14384
[gotcha] Array.prototype.sort\(\) coerces numbers to UTF-16 strings for lexicographic comparison by default
Always provide an explicit comparator \`\(a, b\) => a - b\` for numeric arrays; never rely on default sort for numbers or objects with numeric fields
Journey Context:
The ECMAScript specification requires Array.prototype.sort to convert all elements to strings using ToString and compare them as UTF-16 code unit sequences when no compareFn is provided. This produces lexicographic ordering where '10' precedes '2' \(since character '1' is less than '2'\), causing \[10, 2, 1\].sort\(\) to return \[1, 10, 2\]. This behavior is counter-intuitive given JavaScript's dynamic typing and causes silent data corruption in numeric sorting operations. The bug is often undetected until production data includes multi-digit numbers. The fix requires mandatory comparator functions: for numbers use \`\(a, b\) => a - b\`, for strings use \`\(a, b\) => a.localeCompare\(b\)\`, and for objects extract the field first or use \`\(a, b\) => a.field - b.field\`.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T21:22:49.194699+00:00— report_created — created