BugHunt

sort() puts 10 before 9

Array.prototype.sort() converts items to strings and sorts them alphabetically by default, so 10 comes before 9. Pass a compare function.

JavaScriptLogic errors

What it means

Without an argument, sort() compares UTF-16 strings: "10" < "9" because "1" < "9". It works for single digits, which is why it slips through tests. It also sorts the array in place and returns the same array.

Common causes

1. Sorting numbers without a compare function

The default comparison is alphabetical.

Breaks

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

Works

[10, 9, 100, 1].sort((a, b) => a - b)   // [1, 9, 10, 100]

2. Sorting a copy you thought was separate

sort() mutates the original array.

Breaks

const top = scores.sort((a, b) => b - a).slice(0, 3);

Works

const top = [...scores].sort((a, b) => b - a).slice(0, 3);
// or scores.toSorted((a, b) => b - a)

How to find it in your own code

Always pass a compare function for numbers: (a, b) => a - b ascending, b - a descending. Sort a copy ([...arr] or toSorted()) unless changing the original is intended.

Try it: fix this bug

easy

sortNumbers([10, 2, 30]) returns [10, 2, 30] instead of [2, 10, 30].

function sortNumbers(arr) {
    return arr.sort();
}
Open with hintsRuns in your browser. No account needed.

More challenges with this error

Each of these challenges runs into this exact error. Find the bug and fix it in your browser — no install, no account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Other common errors