Reverse JavaScript Arrays Immutably with `toReversed()`
1
min read .
Updated on
toReversed() returns a new array with the elements in reverse order while leaving the original array unchanged. It is the non-mutating counterpart to reverse().
Basic Usage
const originalArray = [1, 2, 3, 4, 5];
const reversedArray = originalArray.toReversed();
console.log(reversedArray); // [5, 4, 3, 2, 1]
console.log(originalArray); // [1, 2, 3, 4, 5]
toReversed() vs. reverse()
const a = [1, 2, 3];
const b = a.reverse();
console.log(a); // [3, 2, 1]
console.log(b === a); // true
reverse() changes the existing array. By contrast:
const a = [1, 2, 3];
const b = a.toReversed();
console.log(a); // [1, 2, 3]
console.log(b); // [3, 2, 1]
Combine It with Other Array Methods
const numbers = [1, 2, 3, 4, 5];
const reversedAndDoubled = numbers.toReversed().map((n) => n * 2);
console.log(reversedAndDoubled); // [10, 8, 6, 4, 2]
This is useful in state-management and UI code where mutating shared arrays can lead to subtle bugs.
Compatibility
toReversed() is part of the newer copy-by-change array APIs. If you target older JavaScript runtimes, use a compatibility layer or the traditional copy-and-reverse pattern:
const reversed = [...originalArray].reverse();Conclusion
Use toReversed() when you need a reversed view of an array without changing the source data. It makes non-mutating intent explicit and removes the need to clone before calling reverse().