⚡ JavaScript: Fix an Array Sort Comparator Breaking on a NaN Result
Array.prototype.sort’s comparator contract requires returning a negative, zero, or positive NUMBER for every pair it’s asked to compare, and a comparator written as (a, b) => a.value – b.value silently returns NaN the instant either value is itself NaN – a parsed number that failed to parse, a missing field defaulting to undefined used in arithmetic – because any arithmetic involving NaN produces NaN. The language spec leaves a sort’s behavior unspecified once the comparator returns NaN for some pair, so different engines, and even the same engine at different array sizes, can leave the affected elements in silently unpredictable order instead of throwing anything that would point at the actual cause.
🔎 The Problem
const items = [
{ name: 'Widget', price: '19.99' },
{ name: 'Gadget' }, // no price field at all
{ name: 'Gizmo', price: '4.50' },
];
items.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
// parseFloat(undefined) -> NaN for 'Gadget'
// comparator returns NaN whenever 'Gadget' is compared against anything
// -> 'Gadget' can land in an unpredictable position, varies by engine
✅ The Fix
- Validate or default every value a numeric comparator relies on BEFORE sorting (filter out, or coerce missing/invalid values to a defined fallback) instead of discovering a NaN only once it’s already inside the comparator.
- Write the comparator defensively with explicit checks (if (Number.isNaN(diff)) return 0;, or push NaN-producing entries to a defined position) rather than trusting that subtraction will always produce a well-behaved number.
- Add a test case with at least one malformed or missing value in the array being sorted, not only clean data, since a sort that looks completely correct on well-formed test data can still hide a NaN comparator contract violation.
🚨 Why This Is Dangerous
An unpredictable order affecting only the malformed entries is easy to miss in casual testing – most of the list sorts correctly and only the NaN-affected rows land somewhere unexpected, which looks like a rare, hard-to-reproduce flake rather than a deterministic rule violation it actually is.
A sort comparator that can return NaN hasn’t just made a mistake about ordering – it’s broken the one contract Array.prototype.sort actually depends on.





