Course contentsShow
← JavaScript
Lesson 834 of 2,72319. ArraysFree lesson

toSorted() for Immutable Sorting

Create a sorted copy of an array while leaving the original unchanged.

toSorted() for Immutable Sorting

What You'll Learn: How to create a sorted copy of an array without changing the original array.

The Problem with sort()

You've already learned about sort(), which sorts an array in place, meaning it changes the original array. Sometimes you want a sorted version but need to keep the original unchanged—for example, when displaying data in multiple orders or preserving history.

Enter toSorted()

The toSorted() method creates a new sorted array while leaving the original untouched. It works exactly like sort(), but instead of mutating, it returns a fresh copy.

const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.toSorted();

console.log(sorted);   // [1, 1, 3, 4, 5]
console.log(numbers);  // [3, 1, 4, 1, 5] — unchanged!

Using with Comparator Functions

Just like sort(), you can pass a comparator function to control the sorting logic:

const scores = [85, 92, 78, 95];

// Sort descending (highest first)
const descending = scores.toSorted((a, b) => b - a);

console.log(descending);  // [95, 92, 85, 78]
console.log(scores);      // [85, 92, 78, 95] — original intact

Why This Matters

Think of toSorted() like making a photocopy of a document, then organizing the copy—your original stays in its messy drawer. This is crucial when multiple parts of your code need the same data in different orders, or when you want to avoid accidental side effects.

Key Takeaway: Use toSorted() when you need a sorted array but must preserve the original—it's the immutable alternative to sort().