Learn JavaScript
❯ arrays.sort

Sorting with sort() in JavaScript

$concept

Array.prototype.sort sorts in place (mutating!) with an optional comparator (a, b) => number: negative puts a first, positive puts b first, zero keeps order. The infamous default — no comparator means string comparison, so [10, 9, 80] sorts as [10, 80, 9] — bites every beginner exactly once.

Modern engines guarantee stable sort (equal elements keep original order), numeric sorts need (a, b) => a - b, and non-mutating sorts use toSorted() (ES2023) or slice().sort(). Comparators must be consistent (transitive) or results are implementation-defined garbage.

$how it works
1

Default is lexicographic

No comparator sorts as strings — [10, 9, 80] becomes [10, 80, 9]. Always pass a comparator for numbers.

2

Comparators return numbers

(a, b) => a - b ascends; b - a descends; localeCompare for strings; multi-field with || chains.

3

In place (usually)

sort() mutates and returns the same array — copy via [...arr].sort() or toSorted() to preserve originals.

4

Stable and consistent

Equal elements keep original order (guaranteed); inconsistent comparators produce undefined arrangements.

$example
let nums = [10, 9, 80];
nums.sort();
console.log(nums);
nums.sort((a, b) => a - b);
console.log(nums);
Output
[ 10, 80, 9 ]
[ 9, 10, 80 ]
1Bare sort() orders lexicographically as strings — 10, 80, 9 — the classic trap demonstrated live.
2The numeric comparator (a, b) => a - b re-sorts ascending to 9, 10, 80.
3Both lines together prove the rule: default string order versus explicit numeric order.
$use cases
Numeric sorts always with explicit comparators
String sorts with localeCompare for language-correct order
Non-mutating sorts via spread-copy or toSorted()
Multi-criteria sorts chaining comparators with ||

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.