❯ehsan.blog
~/blog/your-sort-does-nothing-in-node-and-works-in-bun — zsh
❯cat your-sort-does-nothing-in-node-and-works-in-bun.md

Your sort does nothing in Node and works in Bun

·6 min read

Your sort does nothing in Node and works in Bun — article card for a post by Ehsan Shahid

A list of users was coming out in the wrong order in production. Not scrambled, not reversed. Just the order the database handed them to me, as if the sort had never run.

It ran. I added a log line to prove it. It ran, and it did nothing.

Locally the same page was perfectly sorted. I develop with Bun and deploy to Node, and that turned out to be the whole story.

The line

js
users.sort((a, b) => a.age > b.age)

Read that out loud. “Sort users by: a’s age is greater than b’s age.” It sounds like English. It passed review twice.

Here is what it does, on real data:

js
const users = [
  { n: 'zoe',  age: 31 },
  { n: 'amir', age: 24 },
  { n: 'lin',  age: 45 },
]

users.sort((a, b) => a.age > b.age)
console.log(users.map(u => u.n).join(','))
plaintext
node  →  zoe,amir,lin     (unchanged)
bun   →  amir,zoe,lin     (correctly sorted)

Same file. Same JavaScript. Node 22.16 and Bun 1.3.10, run one after the other.

What a comparator is actually asked

sort does not want a yes or no. It wants a number, and it reads the sign of that number as an instruction:

  • negative means “put a before b”
  • zero means “these two are tied, leave them alone”
  • positive means “put a after b”

Three answers. Your function is only able to give two.

a.age > b.age returns true or false. When sort turns those into numbers it gets 1 and 0. Positive and zero. There is no way for this function to ever return a negative number, which means it can never once say “put a before b”.

That is the whole bug. The comparator has no word for “earlier”.

Why Node freezes and Bun is fine

A comparator that never returns a negative number is not a valid comparator, and the language spec does not say what should happen next. Each engine is free to do whatever falls out of its own sorting code, so they disagree.

I wanted numbers rather than a guess, so I ran 2,100 random arrays through it, with lengths from 2 up to 1,000:

EngineCame out sortedCame out completely unchanged
Node 22.16 (V8)2122,100
Chromium (V8)1702,100
Bun 1.3.10 (JavaScriptCore)2,100231

V8 left all 2,100 arrays exactly as they were. Every single one. The handful that count as “sorted” were two-item arrays that happened to already be in order before the call.

Bun sorted all 2,100 correctly. The 231 unchanged ones were short arrays that were already sorted to begin with.

So in Node and in Chrome, .sort() with a boolean comparator is not “a bit wrong”. It is a no-op. The array comes back untouched:

js
[5, 3, 9, 1, 7, 2].sort((a, b) => a > b)
// node:  [5, 3, 9, 1, 7, 2]
// bun:   [1, 2, 3, 5, 7, 9]

This is the detail that makes the bug so expensive. A function that sorts badly gets caught in five minutes, because the output looks wrong immediately. A function that returns your input unchanged looks fine on any data that arrived roughly in order already, and it looks perfect on a machine whose engine quietly covers for you.

The near miss that looks like the fix

The repair most people reach for first is a ternary:

js
rows.sort((a, b) => (a.level > b.level ? 1 : -1))

Now there is a negative number, so things really do move. But look at what it says when two items are equal: a.level > b.level is false, so it answers -1, which means “put a first”. It claims one of them wins even when neither does.

Items that are tied get reordered. With five rows at two levels, numbered in their original order:

plaintext
input   a0  b1  a2  b3  a4
output  a4  a2  a0  b3  b1

The groups are right. Inside each group everything is backwards. I got the same reversed output on both Node and Bun, 2,000 runs out of 2,000, so this one is not even engine-dependent. It is just wrong everywhere, consistently, which is somehow worse because it will look stable in testing.

If the order of equal items is meaningful to you, and it usually is once a user has sorted a table by a second column, this silently throws that away.

The versions that are actually correct

Numbers. Subtract. Subtraction already produces a negative number, a zero, and a positive number, which is exactly the three answers sort asked for:

js
users.sort((a, b) => a.age - b.age)       // youngest first
users.sort((a, b) => b.age - a.age)       // oldest first

Strings. Use localeCompare. It returns the same three-way answer, and it handles accented letters the way a human reading that language would expect:

js
names.sort((a, b) => a.localeCompare(b))

Not numbers. Calling .sort() with no comparator at all does not compare numbers. It turns everything into strings first, so 10 sorts before 9 because the text "1" comes before "9":

js
[10, 9, 100, 1].sort()
// [1, 10, 100, 9]

That one behaves identically in Node and Bun. It has always been this way, and it is the reason the subtraction form exists.

The check that catches it

Drop this next to any comparator you are unsure about. It fails loudly instead of waiting for production:

js
import assert from 'node:assert'

const byAge = (a, b) => a.age - b.age

const input = [
  { n: 'zoe',  age: 31 },
  { n: 'amir', age: 24 },
  { n: 'lin',  age: 45 },
]

// 1. it must actually reorder a shuffled list
assert.deepStrictEqual(
  [...input].sort(byAge).map(u => u.n),
  ['amir', 'zoe', 'lin'],
)

// 2. it must answer all three ways, not two
assert.ok(byAge({ age: 1 }, { age: 2 }) < 0, 'never says "a first"')
assert.ok(byAge({ age: 2 }, { age: 1 }) > 0, 'never says "b first"')
assert.strictEqual(byAge({ age: 1 }, { age: 1 }), 0, 'never says "tied"')

The second block is the one that matters. It asks the comparator the only question that counts: can you give me all three answers? A boolean comparator fails the first assertion in that block, on every engine, including the ones that were covering for it.

What I took from it

The real lesson is not about sort. It is that my laptop and my server run different JavaScript engines, and I had been treating “it works locally” as if it meant “it is correct”.

It does not. It means one engine out of two was willing to guess what I meant.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.