Problem: JavaScript’s .sort mutates the array


Problem: JavaScript’s .sort mutates the array.

Solution: Use .toSorted instead. It returns a new sorted array.

toSorted is new. It's part of ES2023.

Also new:
.toReversed (like .reversed)
.toSpliced (like .splice)

The convention: To avoid mutating the array, use methods that start with "to".

These new methods are already supported in major browsers, Node, and Deno too.

Oops, typo. Meant to say "like .reverse"

View original on X