liveBook · Manning

Sorting algorithm

As explained in JavaScript in Depth

The process of arranging items into a specified order according to a comparison rule.

A comparator such as `(a, b) => a - b` sorts numeric timestamps, but JavaScript also coerces numeric strings during each comparison. That hidden work scales with comparisons, not just the number of items. section 4.4.1 section 4.4.4

Watch for two practical failure modes:

  • Numeric strings can produce the right order at greater cost: sorting 10,000 numbers took about 2.8 ms, versus 12 ms for strings and about 16 ms with millisecond precision. section 4.4.4
  • Subtracting ISO date strings produces NaN. JavaScript treats a NaN comparator result as +0, so the elements compare equal and remain in arrival order. section 4.4.1
const timestamps = [
  '1861-03-04T17:00:00Z',
  '2009-01-20T17:00:00Z',
  '2021-01-20T17:00:00Z'
];
timestamps.sort((a, b) => a - b);

This comparator looks plausible, but subtracting ISO date strings yields NaN rather than a chronological comparison. section 4.4.1

Check input types before sorting, or use a type-safe variant such as TypeScript. Runtime optimizations may reduce conversion costs, but cannot always be relied on. section 4.4.4

How JavaScript in Depth covers it

How deep it goes
Traces per-comparison conversions and explains how NaN comparator results are treated as +0.
Examples
Compares numeric and numeric-string timestamps, then demonstrates an ineffective comparator for ISO date strings.
What you can do after
Diagnose comparator errors and avoid repeated coercion by checking types or using TypeScript.
How it connects
Connects comparator behavior to implicit type coercion, JavaScript, and TypeScript type checking.

Also explained in

Compare how 19 books explain sorting algorithm →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.