Skip to content

toReversed and toSorted

This lesson explains toReversed and toSorted with clear examples, use cases, and best practices so you can use modern JavaScript confidently in real projects.

ES6+ toReversed and toSorted Overview

toReversed() and toSorted() are modern JavaScript array methods that return new arrays without changing the original one. They are part of the immutable array method family introduced to make sorting and reversing safer in functional and state-driven code.

Before these methods, developers often copied an array with [...items] or slice() before calling mutating methods like reverse() and sort(). The new methods express that intent more clearly and reduce accidental mutation bugs.

Feature Description
Introduced In ES2023
Methods toReversed(), toSorted()
Mutates Original No
Returns New array
Replaces reverse(), sort() in immutable workflows
Common Uses UI state, sorting lists, immutable data patterns

Basic toReversed and toSorted Example

const numbers = [3, 1, 4, 2];

const reversed =
  numbers.toReversed();

const sorted =
  numbers.toSorted(
    (a, b) => a - b
  );

console.log(numbers);
console.log(reversed);
console.log(sorted);

The original array stays unchanged, while toReversed() and toSorted() return new arrays with the transformed values.

How toReversed and toSorted Work

Both methods create a shallow copy of the array, apply the transformation, and return the new result. They do not modify the source array or its original order.

Step Description Example Syntax
Start with Array Keep the original data unchanged. const items = [3, 1, 2]
Reverse Copy Return a reversed version. items.toReversed()
Sort Copy Return a sorted version. items.toSorted()
Custom Sort Pass a compare function. items.toSorted((a, b) => a - b)
Use Result Store or render the new array. setState(sorted)
Preserve Source Original array remains intact. console.log(items)

Reverse an Array with toReversed()

const tasks = [
  "Write docs",
  "Fix bug",
  "Review PR"
];

const latestFirst =
  tasks.toReversed();

console.log(tasks);
console.log(latestFirst);

Use toReversed() when you want to display items in reverse order without changing the stored source array.

Sort an Array with toSorted()

const scores = [88, 95, 72, 91];

const ascending =
  scores.toSorted(
    (a, b) => a - b
  );

const descending =
  scores.toSorted(
    (a, b) => b - a
  );

console.log(scores);
console.log(ascending);
console.log(descending);

toSorted() accepts the same compare function as sort(), but returns a new sorted array instead of modifying the original one.

Sort Strings Alphabetically

const names = [
  "Charlie",
  "Alex",
  "Sam"
];

const sortedNames =
  names.toSorted(
    (a, b) =>
      a.localeCompare(b)
  );

console.log(names);
console.log(sortedNames);

For string sorting, use localeCompare() inside toSorted() to get predictable alphabetical order.

Sort an Array of Objects

const products = [
  { name: "Keyboard", price: 79 },
  { name: "Mouse", price: 29 },
  { name: "Monitor", price: 249 }
];

const byPrice =
  products.toSorted(
    (a, b) => a.price - b.price
  );

const byName =
  products.toSorted(
    (a, b) =>
      a.name.localeCompare(b.name)
  );

console.log(products);
console.log(byPrice);
console.log(byName);

Object arrays are a common use case for toSorted() because you often want a sorted view for tables, filters, or dropdowns without mutating the source data.

Use in Immutable State Updates

let posts = [
  { id: 1, title: "Intro to ES2023" },
  { id: 2, title: "Array Methods" },
  { id: 3, title: "Modern JavaScript" }
];

function sortPostsByTitle(items) {
  return items.toSorted(
    (a, b) =>
      a.title.localeCompare(b.title)
  );
}

const sortedPosts =
  sortPostsByTitle(posts);

console.log(posts);
console.log(sortedPosts);

Immutable methods are especially helpful in React, Redux, and other state-driven apps where the original state should not be changed directly.

Why Mutation Can Cause Bugs

const original = [3, 1, 2];

const mutated =
  original.sort(
    (a, b) => a - b
  );

console.log(original);
console.log(mutated);
console.log(
  original === mutated
);
const safeOriginal = [3, 1, 2];

const safeSorted =
  safeOriginal.toSorted(
    (a, b) => a - b
  );

console.log(safeOriginal);
console.log(safeSorted);
console.log(
  safeOriginal === safeSorted
);

sort() changes the original array and returns the same reference. toSorted() avoids that problem by returning a separate array.

Fallback for Older Environments

const values = [5, 2, 9, 1];

const reversed =
  values.toReversed?.() ??
  [...values].reverse();

const sorted =
  values.toSorted?.(
    (a, b) => a - b
  ) ??
  [...values].sort(
    (a, b) => a - b
  );

console.log(reversed);
console.log(sorted);

If you need to support older browsers, use optional chaining with spread-copy fallbacks that mimic the non-mutating behavior of the modern methods.

Common toReversed and toSorted Use Cases

  • Sorting table rows without changing source data.
  • Showing newest or oldest items first in a UI list.
  • Preparing immutable state updates in React applications.
  • Sorting search results, tags, or categories for display.
  • Creating derived views from API response arrays.
  • Avoiding accidental mutation in shared utility functions.

toReversed and toSorted Best Practices

  • Prefer toSorted() over sort() when immutability matters.
  • Always provide a compare function for numeric sorting.
  • Use localeCompare() for string sorting.
  • Keep the original array unchanged when rendering UI state.
  • Combine with spread or copy methods only when fallback support is needed.
  • Remember that these methods perform shallow copies.
  • Check browser support or provide fallbacks for older environments.

Common toReversed and toSorted Mistakes

  • Using sort() when the original array must stay unchanged.
  • Forgetting a compare function and getting lexicographic number sorting.
  • Assuming toSorted() modifies the source array.
  • Expecting deep cloning instead of a shallow array copy.
  • Sorting strings without localeCompare().
  • Using these methods in environments without ES2023 support and no fallback.
  • Replacing all sorting logic even when mutation is intentional and safe.

Immutable vs Mutating Array Methods

Feature toReversed / toSorted reverse / sort
Original Array Not changed. Changed in place.
Return Value New array. Same array reference.
Best For State management and derived views. Local temporary mutation when safe.
Bug Risk Lower in shared data flows. Higher when source data is reused.

Key Takeaways

  • toReversed() and toSorted() return new arrays without mutating the original.
  • They are part of the ES2023 immutable array method family.
  • toSorted() accepts the same compare function as sort().
  • They are ideal for UI state, sorting views, and safer functional code.
  • Use fallbacks with spread copies when supporting older browsers.

Pro Tip

If you are building React or immutable state logic, reach for toSorted() and toReversed() first. They make your intent clear and help prevent hard-to-debug mutation issues.