Sorting with sort() in JavaScript
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.
Default is lexicographic
No comparator sorts as strings — [10, 9, 80] becomes [10, 80, 9]. Always pass a comparator for numbers.
Comparators return numbers
(a, b) => a - b ascends; b - a descends; localeCompare for strings; multi-field with || chains.
In place (usually)
sort() mutates and returns the same array — copy via [...arr].sort() or toSorted() to preserve originals.
Stable and consistent
Equal elements keep original order (guaranteed); inconsistent comparators produce undefined arrangements.
let nums = [10, 9, 80];nums.sort();console.log(nums);nums.sort((a, b) => a - b);console.log(nums);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.