Sorting Algorithms in JavaScript
Sorting in JavaScript has a famous gotcha that trips up beginners, plus a modern engine implementation worth understanding. This guide covers Array.prototype.sort(), the compare-function trap, and clean implementations of the classic algorithms.
The Array.sort gotcha
By default, Array.prototype.sort() converts elements to strings and sorts lexicographically — so [10, 2, 1].sort() returns [1, 10, 2]! Always pass a compare function for numbers: arr.sort((a, b) => a - b). This is the single most common JavaScript sorting bug.
What engines use
Since 2018, V8 (Chrome, Node.js) implements Array.prototype.sort() with Tim Sort. The ECMAScript spec has required sort to be stable since ES2019, so behavior on equal elements is now consistent across modern browsers. See JavaScript's Array.sort algorithm for more.
Quick Sort in JavaScript
function quickSort(arr) {
if (arr.length <= 1) return arr;
const [pivot, ...rest] = arr;
const left = rest.filter((x) => x < pivot);
const right = rest.filter((x) => x >= pivot);
return [...quickSort(left), pivot, ...quickSort(right)];
}Frequently asked questions
What algorithm does JavaScript Array.sort() use? +
Why does JavaScript sort numbers incorrectly? +
See it in motion
Watch this algorithm and 9 others run step by step in our free interactive visualizer.
▶ Launch Visualiser