JavaScript sort(): Comparators, Stability and Mutation
Quick answer
sort() rearranges the receiver and returns that same array. With no comparator, defined values are compared as strings by UTF-16 code units.
How it works
A numeric comparator (a, b) => a - b returns negative, positive or zero to indicate ordering. Sorting is stable: equal comparisons preserve original order. Undefined values and holes move to the end (holes after undefined in ordinary arrays). Comparator order and number of invocations are not guaranteed; use a consistent side-effect-free comparator.
console.log([2, 10, 1].sort().join(","));Expected output in Node.js:
1,10,2String ordering puts "10" before "2".
const a = [3, 1, 8];const b = a.sort((x,y)=>y-x);console.log(b.join(","), a === b);Expected output in Node.js:
8,3,1 trueDescending comparator sorts the same receiver.
Common mistakes
sort() is not numeric by default; a comparator returning only true or false cannot reliably express both directions. Copy before sorting if the source must remain intact.
Practice
Sort the same numeric list in ascending and descending order using separate copies.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript sort(): Comparators, Stability and Mutation — Knowledge Check
Apply the taught concept and predict the output.
Which comparator orders ordinary finite numbers ascending?
What does stable sorting mean for records with equal comparison keys?
Does sort guarantee a particular number of comparator calls?
What is the exact console output in JavaScript sort(): Comparators, Stability and Mutation example 1?
console.log([2, 10, 1].sort().join(","));What is the exact console output in JavaScript sort(): Comparators, Stability and Mutation example 2?
const a = [3, 1, 8];const b = a.sort((x,y)=>y-x);console.log(b.join(","), a === b);