Language Implementations

Sorting Algorithms in JavaScript

Updated June 8, 2026 7 min read

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? +
V8 (Chrome, Node.js) uses Tim Sort since 2018. Firefox's SpiderMonkey uses a Merge Sort variant. The spec requires stability since ES2019 but does not mandate a specific algorithm.
Why does JavaScript sort numbers incorrectly? +
Because the default sort converts values to strings and compares them lexicographically. Pass a compare function like (a, b) => a - b to sort numbers correctly.

See it in motion

Watch this algorithm and 9 others run step by step in our free interactive visualizer.

▶ Launch Visualiser

Related articles

← Back to all articles