JavaScript (ES2026) reference · Array Methods

JavaScript Array sort() Method

Sort the array in place and return it. Without a compare function elements are sorted as strings, so numbers need one.

JavaScript (ES2026) Since ES1

Syntax

array.sort(compareFn)

Parameters

ParameterDescription
compareFn optional Returns a negative number if a comes first, positive if b does, 0 if equal.

Return value

The same, sorted array.

Examples

Sorting numbers correctlyTry it yourself
console.log([10, 9, 1, 100].sort()); // compared as strings!
console.log([10, 9, 1, 100].sort((a, b) => a - b));

Output

[ 1, 10, 100, 9 ]
[ 1, 9, 10, 100 ]
Sort objects by a string propertyTry it yourself
const people = [{ name: "Linus", age: 28 }, { name: "Ada", age: 36 }];
people.sort((a, b) => a.name.localeCompare(b.name));
console.log(people.map((p) => p.name));

Output

[ 'Ada', 'Linus' ]
Keep the original with toSorted()Try it yourself
const original = [3, 1, 2];
const sorted = original.toSorted((a, b) => a - b);
console.log(original, sorted);

Output

[ 3, 1, 2 ] [ 1, 2, 3 ]

Common mistakes

  • Without a compare function, [10, 9, 1].sort() gives [1, 10, 9]: elements are compared as strings. Use (a, b) => a - b for numbers.
  • sort() changes the array. Use toSorted() (ES2023) or sort a copy ([...arr].sort()).
  • The sort is stable (guaranteed since ES2019).

Version history

VersionChange
JavaScript ES1Added
JavaScript ES2019The sort is guaranteed to be stable.

In other languages