Sort Comparators Must Return Numbers

Comparators returning booleans only produce 0 or 1, so descending swaps never apply; subtract the fields instead to get a numeric comparator.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
const scores = [
  { name: "ada", points: 12 },
  { name: "bo", points: 9 },
  { name: "cy", points: 12 },
];

// A boolean comparator only ever yields 0 or 1: true reads as
// "a goes after b", false as "leave this pair alone", so no
// comparison ever signals "move a before b"
const broken = [...scores].sort((a, b) => a.points > b.points);
console.log("broken:", broken.map((s) => s.name + ":" + s.points)); // input order came back

// A comparator must return a number: negative, zero, or positive
const byPointsDesc = [...scores].sort((a, b) => b.points - a.points);
console.log("fixed:", byPointsDesc.map((s) => s.name + ":" + s.points));

// sort is stable since ES2019: ada and cy tie, ada keeps its lead
console.log("tie order:", byPointsDesc.map((s) => s.name));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

broken: [ 'ada:12', 'bo:9', 'cy:12' ]
fixed: [ 'ada:12', 'cy:12', 'bo:9' ]
tie order: [ 'ada', 'cy', 'bo' ]

How it works

Top-level bindings scores, broken, byPointsDesc hold the demo state — nothing sits inside a function scope.

Watch out for

  • No package installation, no environment variables, no setup steps.

Using it

Output lines are prefixed (broken:, fixed:, tie order:), which makes the step behind each line recoverable from the text.

Key statements

const byPointsDesc = [...scores].sort((a, b) => b.points - a.points);
const broken = [...scores].sort((a, b) => a.points > b.points);

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. Its state lives in module-level bindings: `scores`, `broken`, `byPointsDesc`.