toReversed() in JavaScript ES2023

toReversed() method in JavaScript

The toReversed() method, introduced in ES2023, is a new addition to the Array.prototype object that allows you to create a new array containing the elements of the original array in reversed order. It's specifically designed to avoid modifying the original array, promoting immutability, and preventing unintended side effects in your code.

Functionality of toReversed() method

  • Creates a new array: Unlike the existing reverse() method, which mutates the original array, toReversed() creates a copy with the elements reversed.
  • Preserves the original array: This ensures that the original array remains unchanged, making it suitable for scenarios where you need to work with both the original and reversed versions independently.

Benefits of JavaScript ES2023

  • Immutability: By creating a new array instead of modifying the original, toReversed() promotes immutability, leading to cleaner and more predictable code.
  • Reduced risk of side effects: Since the original array remains untouched, you don't have to worry about accidental modifications that might affect other parts of your code.

In a nutshell, toReversed() provides a safe and efficient way to create reversed copies of arrays in ES2023, promoting a more functional and immutable coding style.

Example with Output

const originalArray = ['a', 'b', 'g', 'h', 'z'];
const reversedArray = originalArray.toReversed();

console.log(oroginalArray);
console.log(reversedArray);

Example with output