Favorites

JavaScript Array.prototype.sort() Method

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
Array.prototype.sort()
JavaScript Array Instance methodThis method is supported by all modern browsers.
Updated 28th November 2026

The sort() method sorts the elements of an array in place. Without a compare function it sorts as strings, so numbers need a function like (a, b) => a - b.

Description

The sort() method sorts an array in place and returns it. Without a compare function, elements are converted to strings and sorted by UTF-16 code units, which puts 10 before 9 and capital letters before lowercase ones.

Pass a compare function to sort properly: (a, b) => a - b sorts numbers ascending, and (a, b) => a.name.localeCompare(b.name) sorts objects by a text property. The sort is stable, so equal elements keep their original order. Use toSorted() to get a sorted copy instead of changing the original.

Sorting is done in place and the same array is returned, so const sorted = arr.sort() also sorts arr. undefined values are always moved to the end without calling the compare function, and empty slots come after them. For sorting text in a language-aware way, pass new Intl.Collator().compare, which also handles accents and numbers inside text.

Syntax

array.sort()
array.sort(compareFn)

Parameters

  • compareFnOptional. A function (a, b) that returns a negative number if a should come first, a positive number if b should, or 0 to keep their order.

Return Value

The same array, now sorted.

Example

const nums = [10, 9, 1, 100];
console.log([...nums].sort());              // as strings
console.log([...nums].sort((a, b) => a - b));

const people = [{ name: 'Zoe', age: 30 }, { name: 'Adam', age: 25 }];
people.sort((a, b) => a.name.localeCompare(b.name));
console.log(people.map(p => p.name));

Browser Support

The following information will show you the current browser support for the Array.prototype.sort() method. Hover over a browser icon to see the version that first introduced support for this method.

This method is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee