CKTIS / JavaScript
Sorting and comparing array elements
Sorting orders elements according to a comparison rule. Learn the default textual order, numeric comparators, stability, and the difference between mutating sort() and copying toSorted().
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
array.sort(compareFn)
array.toSorted(compareFn)
compareFn(a, b) // Number: < 0, 0, > 0Sorting arranges elements according to a comparison rule. array.sort(compareFn) modifies the array and returns that same array. Without compareFn, it compares elements' string representations lexicographically by UTF-16 code units, not numerically: [10, 2, 1].sort() produces [1, 10, 2].
A comparator receives a and b and returns a Number: negative when a belongs earlier, positive when it belongs later, or 0 when the elements have equal priority. For finite numbers, (a, b) => a - b sorts ascending and (a, b) => b - a descending. Do not use (a, b) => a > b: a Boolean result does not correctly describe all three cases. A comparator should be deterministic, avoid modifying the compared data, and preserve sign consistency when arguments are swapped and transitivity. A NaN result is treated as 0.
Sorting is stable: elements that compare equal retain their original order. You can therefore sort objects by a field without changing the order of ties. The specification does not mandate a particular algorithm or time or space complexity guarantees. In ordinary arrays, undefined goes after other values without invoking the comparator for it; sort() places empty slots after undefined.
array.toSorted(compareFn) has been standardized since ECMAScript 2023 and returns a new, shallow copy in sorted order. It uses ordinary property lookup at each index, so an index with no own property can still yield an inherited value. The lookup yields undefined only if no property is found or the property itself yields undefined. Before using it, check typeof Array.prototype.toSorted === "function" in the target environment; availability in Node.js does not prove browser support. The example uses [...numbers].sort(...) to preserve the original dense array without requiring toSorted().
Examples
const numbers = [10, 2, 1];
const lexical = [...numbers].sort();
const numeric = [...numbers].sort((a, b) => a - b);
console.log(JSON.stringify(lexical));
console.log(JSON.stringify(numeric));
console.log(JSON.stringify(numbers));Result
[1,10,2] [1,2,10] [10,2,1]
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.