Report #95665
[gotcha] Array.prototype.sort comparator returning NaN treats elements as equal rather than throwing
Avoid arithmetic that can produce NaN in comparators. Use explicit three-way comparison: \(a, b\) => \(a < b ? -1 : a > b ? 1 : 0\). If values might be undefined, normalize them before comparison to avoid NaN propagation.
Journey Context:
When Array.prototype.sort's comparator returns NaN, the ECMAScript specification mandates treating it as \+0, meaning the elements are considered equal for sorting purposes. This silent coercion differs from mathematical conventions where NaN comparisons are always false. Developers often write numeric comparators like \(a, b\) => a.value - b.value without checking for undefined or non-numeric values, which produces NaN. Since the sort algorithm remains stable, these elements retain original relative order, but the bug is silent and can cause data to appear correctly ordered when it isn't. Explicit three-way comparison avoids arithmetic entirely, eliminating NaN generation and clearly expressing sorting intent.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T19:09:20.430337+00:00— report_created — created