DEV Community


Posted on • Originally published at on

Future-Proof Your JavaScript Code

Future-Proof Your JavaScript Code: The Game-Changing Immutability Revolution


In this article, we will explore a set of new array methods that offer a fresh approach to achieving immutability.

The methods under discussion are with, toSorted, toReversed, and toSpliced.

Immutability ensures that the original array remains unchanged, and modifications are made on a new copy. While there were existing techniques for achieving immutability, such as utilizing the spread operator, these new array methods present more convenient alternatives.

These methods offer improved code readability and performance benefits, making them advantageous for developers.

  1. with() Method

The with() method of Array instances is the copying version of using the bracket notation to change the value of a given index. It returns a new array with the element at the given index replaced with the given value.

array.with(index, value) — will return a new array with the element at index replaced with value.

const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

2. toSpliced()

splice() — is method that will work on your original array, rather that on their copy.

For eg: — in below example, splice has replaced the start and end index with the new value i.e. ““mango””

what toSpliced() will do, it will not update the original array, rather than work on its copy and original array remains intact. It returns a new array instead of modifying the original array.

3. toSorted()

Normally, we do sort by adding sort() after any array, and it will sort the original array, there is a change in original array.

To remain intact with original array, you need to introduced spread operator and create a separate copy of that like this.

To remove this step, javascript has a new array method, there is no need to use the spread operator ie. toSorted()

4. toReversed()

This method is working same as array.reverse(), but rather than changing original array, it will create a new copy and original array remains intact.

Before using, any of these methods, please check their browser compatibility as many of them is not supported in Firefox, so make use if required.

Also please make sure to check MDN Websiteto check for upcoming features in Javascript.

Thanks for reading

Top comments (0)