transformation

Array.prototype.sort

Sorts the array in place and returns the same array; without a compareFn elements are coerced to strings and sorted lexicographically. Reach for it when you need ordered data — but always pass a compareFn for numbers.

arr.sort([compareFn])

Parameters

Parameter Purpose
compareFn(a, b) Return <0 to place a first, >0 to place b first, 0 to keep order
(no compareFn) Elements are converted to strings and compared by UTF-16 code units

Examples

console.log([10, 1, 21, 2].sort());

Logs: [1, 10, 2, 21] (string sort — beginner gotcha!)

console.log([10, 1, 21, 2].sort((a, b) => a - b));

Logs: [1, 2, 10, 21] (numeric ascending)

const arr = [3, 1, 2]; arr.sort(); console.log(arr);

Logs: [1, 2, 3] — sort MUTATES the original array

console.log([3, 1, 2].toSorted());

Logs: [1, 2, 3] and leaves the original untouched (ES2023 non-mutating alternative)

Gotcha

MUTATES the original array AND returns it — a common beginner bug. Default sort is lexicographic, so [10, 2] sorts as [10, 2]. Use `toSorted()` (ES2023) for a non-mutating copy.

Related methods

← All JS array methods · TypeScript vs JavaScript