CKTIS / JavaScript
Array.prototype.sort: stable in-place ordering
sort orders the elements of the same array, optionally with a comparison function, and returns that array object.
Version: ECMAScript 2026 draft; stable ordering required since ECMAScript 2019; example target: Node.js 24.22.2
Syntax
array.sort(compareFn?)array.sort(compareFn?) collects existing elements and sorts them in place. Its return value is the same array object. With compareFn(a, b), a negative result places a before b, a positive result after b, and zero or NaN preserves their relative order. Sorting is required to be stable since ES2019. The callback is never given undefined.
Without compareFn, non-undefined values are converted to strings and compared by UTF-16 code units, so [80, 9, 100] becomes [100, 80, 9]. Every undefined follows the other values; empty slots follow those values and remain holes.
The method mutates its receiver; use toSorted() or copy first when mutation is unwanted. It is generic for array-like objects: it reads length, writes sorted properties, and deletes trailing missing indexes. A non-callable compareFn throws TypeError; failures from conversion, the callback, accessors, proxy traps, writes, or deletion propagate.
Examples
const tasks = [
{ label: "deploy", priority: 2 },
{ label: "test", priority: 1 },
{ label: "docs", priority: 2 },
];
const returned = tasks.sort((a, b) => a.priority - b.priority);
console.log(returned === tasks);
console.log(tasks.map(({ label, priority }) => `${label}:${priority}`).join("|"));
const numbers = [80, 9, 100];
numbers.sort();
console.log(numbers.join(","));
const sparse = [3, , undefined, 1];
sparse.sort();
console.log(sparse.length, 2 in sparse, 3 in sparse, sparse[0], sparse[1], String(sparse[2]));Result
true test:1|deploy:2|docs:2 100,80,9 4 true false 1 3 undefined