Mastering the toReversed() Method in JavaScript
Introduction
The toReversed() method in JavaScript is a modern array method that **returns a new array with the elements reversed**, without modifying the original array. 🔄 It is a safer alternative to reverse() when you want to preserve immutability.
📌 What is toReversed()?
Unlike reverse(), which modifies the original array in place, toReversed() creates a **new reversed array**, leaving the original unchanged. This makes it ideal for functional programming or scenarios where you want to avoid side effects.
- ✔️ Returns a new array with reversed elements
- ⚡ Does not mutate the original array
- 🔄 Can be chained with other array methods
💡 Syntax
Basic Syntax
array.toReversed()🧵 Example: Basic Usage
Basic toReversed example
const arr = [1, 2, 3, 4];
const reversedArr = arr.toReversed();
console.log(reversedArr); // [4, 3, 2, 1]
console.log(arr); // [1, 2, 3, 4] (original array unchanged)🔗 Example: Chaining with map()
Chain toReversed with map
const arr = [1, 2, 3, 4];
const result = arr.toReversed().map(x => x * 2);
console.log(result); // [8, 6, 4, 2]
console.log(arr); // [1, 2, 3, 4]🍏 Example: Using on Strings (via split)
Reverse string immutably
const str = "hello";
const reversedStr = str.split("").toReversed().join("");
console.log(reversedStr); // "olleh"⚠️ Important Notes
Note
- Does **not modify the original array**, unlike reverse().
- Available in **modern JavaScript environments** (ES2023+).
- Can be combined with other array methods for functional programming patterns.
📊 Quick Reference Table
| Code | Output |
|---|---|
| [1, 2, 3].toReversed() | [3, 2, 1] |
| ['a','b','c'].toReversed() | ['c','b','a'] |
| "abc".split("").toReversed().join("") | "cba" |
>>"toReversed() lets you reverse arrays immutably — safer, cleaner, and perfect for modern JavaScript." ✨
🔥 Summary
toReversed() is the modern, immutable alternative to reverse(). Use it whenever you want a reversed array **without affecting the original**, making your code safer and more predictable.