Array.prototype.sort()
Sorts the elements of an array in place and returns the same array.
Syntax
arr.sort(compareFn) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
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
| Environment | Since version |
|---|---|
| chrome | 1.0 |
| firefox | 1.0 |
| safari | 1.0 |
| edge | 12 |
| node | 0.10 |