Use the ‘With’ method to update an array without mutating

PaperInFlames
May 31, 2023

--

In JavaScript, we can achieve the immutability of an array, by taking a copy of the original array with the Spread operator and performing the required operations on the copied array.

For Example :

We have a team of three members. Where Helen went on long leave. So, Noah joined the team temporarily replacing Helen. Then we can update the team members array as below

Output :

Here, we can achieve the same without copying the actual array in the by. using the new pre-defined method ‘With’ of an array.

Note:

In the same way, we can use toSorted() instead of sort(), toReversed() instead of reverse(), and toSpliced() instead of splice() methods respectively.

Hope this helps 😀🫠

--

--