Array.prototype.sort()

Sorts the elements of an array in place and returns the same array.

Since ES1 Spec ↗

Syntax

arr.sort(compareFn)

Parameters

NameTypeRequiredDescription
compareFn Function No Function (a, b) returning a negative number if a comes first, positive if b comes first, 0 if equal. If omitted, elements are sorted as strings.

Returns

Array — The sorted array (the same reference, not a copy).

Examples

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

Notes

Mutates the array in place. The default comparison converts to strings, which misorders numbers - always pass a comparator for numbers. Sort is stable in modern engines (ES2019+). Use `toSorted` for a non-mutating version.

Browser & runtime support

EnvironmentSince version
chrome 1.0
firefox 1.0
safari 1.0
edge 12
node 0.10

See also