Skip to main content

What does toSorted() do?

toSorted() is a new, non-mutating counterpart to the sort() method in JavaScript, added in the ECMAScript 2023 (ES14) standard.

It lets you sort an array, but does not change the original array - it returns a new sorted copy.

Syntax:

javascript
const newArray = array.toSorted(compareFn);
ParameterDescription
compareFn(optional) comparison function, same as sort() - (a, b) => a - b

Example:

javascript
const numbers = [3, 1, 4, 2]; const sorted = numbers.toSorted((a, b) => a - b); console.log(sorted); // [1, 2, 3, 4] console.log(numbers); // [3, 1, 4, 2] - the original array did not change

Unlike sort(), which mutates the original, toSorted() returns a new array with the elements sorted.

Comparison with sort()

MethodChanges the original arrayReturnsSafe
sort()YesThe same arrayNo
toSorted()NoA new arrayYes

Comparison example:

javascript
const arr = [5, 2, 9]; const sorted1 = arr.sort(); // mutates const sorted2 = arr.toSorted(); // does not mutate console.log(arr); // [2, 5, 9] - mutated! console.log(sorted1); // [2, 5, 9] console.log(sorted2); // [2, 5, 9] - a new independent array

Sorting numbers:

javascript
const nums = [10, 2, 5, 1]; const asc = nums.toSorted((a, b) => a - b); const desc = nums.toSorted((a, b) => b - a); console.log(asc); // [1, 2, 5, 10] console.log(desc); // [10, 5, 2, 1] console.log(nums); // [10, 2, 5, 1] - unchanged

When to use it

  • When it matters to preserve the original data (for example, in React, Redux, functional code).
  • When you need to sort data safely, without side effects.
New methodOld counterpartWhat it doesMutates?
toReversed()reverse()Reverses the orderNo
toSorted()sort()SortsNo
toSpliced()splice()Removes / inserts elementsNo
with()arr[index] = valueReplaces an element by indexNo

Summary:

What it doesCreates a sorted copy of the array
Changes the original arrayNo
ReturnsA new array
Supports a comparison functionYes
Example[3,1,2].toSorted((a,b)=>a-b) -> [1,2,3]

In short: toSorted() is a safe, non-mutating alternative to sort(), which returns a new sorted array, keeping the original unchanged.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.