reverse() vs toReversed()
toReversed() are two commonly used methods, each having its unique
functionality and application.
Array.prototype, alters the
order of the array's elements, essentially flipping them. This method performs
the operation in-place, implying that it directly modifies the original array.
Let's consider the example below:
In the above code, after applying
reverse(), the original fruits array is also
reversed. This is because
reverse() is a destructive method and modifies the
original array in-place.
In contrast to reverse(), the
toReversed() method does not mutate the original array.
Instead, it creates a new array, mirroring the elements of the original array in reverse order.
This method comes handy when preserving the initial order of elements is crucial.
Let's consider a similar example:
In this example, the original numbers array remains unaffected after applying the
toReversed() method, exhibiting its non-destructive nature.
Here, the empty slot in the array is considered as undefined when reversed.
ECMAScript 2023 specification brings about a significant proposal
named Change Array by Copy. This proposal enriches the
set of methods on
Array.prototype by introducing a suite of functions that operate on
the array and return a new copy, instead of manipulating the original array.
The newcomers to this function suite include
toSpliced(), and an
additional method named
These methods are designed to mirror the behavior of existing
and splice(), and the typical array element replacement operation
performed using bracket notation. However, these new methods ensure that the
original array remains unaltered.
The toSorted() method, just like sort(), arranges the array elements in a certain order. The crucial difference is that it does not modify the original array.
toSpliced() acts as a non-destructive version of splice(). It returns a new array,
incorporating the changes specified by the arguments, while the original array stays intact.
with() method is an invaluable tool that replaces an element at
a specified index with a given value and returns a new array, without touching
the original array.
For me personally, these new features significantly simplify array manipulation, particularly in scenarios where avoiding side effects is critical. By preventing accidental mutations, these methods make the code more predictable and easier to reason about, which is a key factor in reducing bugs and enhancing code readability.
In conclusion, the ECMAScript 2023 'Change Array by Copy' proposal introduces toReversed(), toSorted(), toSpliced(), and with(), paving the way for cleaner and more predictable code by offering non-destructive alternatives to traditional array manipulation methods.
Thanks for reading 🥰!
Well, now what?
You can navigate to more writings from here. Connect with me on LinkedIn for a chat.