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);| Parameter | Description |
|---|---|
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 changeUnlike sort(), which mutates the original,
toSorted() returns a new array with the elements sorted.
Comparison with sort()
| Method | Changes the original array | Returns | Safe |
|---|---|---|---|
sort() | Yes | The same array | No |
toSorted() | No | A new array | Yes |
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 arraySorting 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] - unchangedWhen 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.
Related non-mutating methods (ES2023+)
| New method | Old counterpart | What it does | Mutates? |
|---|---|---|---|
toReversed() | reverse() | Reverses the order | No |
toSorted() | sort() | Sorts | No |
toSpliced() | splice() | Removes / inserts elements | No |
with() | arr[index] = value | Replaces an element by index | No |
Summary:
| What it does | Creates a sorted copy of the array |
|---|---|
| Changes the original array | No |
| Returns | A new array |
| Supports a comparison function | Yes |
| Example | [3,1,2].toSorted((a,b)=>a-b) -> [1,2,3] |
In short:
toSorted()is a safe, non-mutating alternative tosort(), which returns a new sorted array, keeping the original unchanged.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.