Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
JavaScript

JavaScript: Fix an Array Sort Comparator Breaking on a NaN Result

- 26.11.26 - ErcanOPAK

⚡ 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.

— JavaScript Tip

Related posts:

JavaScript Memory Grows Without Errors

JavaScript Memory Grows Without Errors

JavaScript: Why structuredClone Throws on Data That JSON.stringify Handled Just Fine

JavaScript: Why structuredClone Throws on Data That JSON.stringify Handled Just Fine

JavaScript: Clean Your Code with Optional Chaining and Nullish Coalescing

JavaScript: Clean Your Code with Optional Chaining and Nullish Coalescing

Views: 5
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

Asp.Net Core: Fix Health Checks Reporting Healthy During an Outage
Photoshop: Fix a Batch Action Skipping Non-Latin Filenames

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,080 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 999 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 998 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 874 views
  5. 05How to select distinct rows in a datatable in C# 869 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 673 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 632 views
  8. 08Average of all values in a column that are not zero in SQL 586 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 563 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com