Embracing Array Immutability with Copy Changes

A New Chapter in JavaScript. 2023

Gerardo Fernández
3 min readMay 10

--

Photo by Michael Dziedzic on Unsplash

JavaScript, a language that has continuously evolved since its inception, is once again ready to surprise us. This time, it brings a new proposal in the realm of array manipulation methods, which is known as “Change Array by Copy”:

This proposal, put forth by Ashley Claymore and Robin Ricard, aims to revolutionize the way we deal with arrays by advocating for immutability.

Immutability, an essential aspect of functional programming, reduces bugs and complications arising from shared state and mutable data. Embracing immutability helps programmers write safer and more predictable code. This is where the Change Array by Copy proposal steps in.

Unleashing the Power of “Change Array by Copy”

JavaScript’s existing array manipulation methods like reverse(), sort(), and splice() mutate the array in place. Though useful in many scenarios, these methods can lead to unexpected side effects when dealing with shared state, especially in complex applications.

The Change Array by Copy proposal introduces new methods that create a new copy of the array, leaving the original array unchanged. These methods are toReversed, toSorted, and toSpliced. They act as immutable counterparts to reverse(), sort(), and splice(), respectively.

An additional method, with(), is also introduced. This method provides a more intuitive way to replace an element at a specific index without mutating the original array.

Let’s explore these new methods.

Exploring toReversed

The toReversed method returns a new array that is the reverse of the original array, leaving the original array unchanged. Here’s how it works:

const original = [1, 2, 3, 4];
const reversed = original.toReversed();

console.log(original);
// [ 1, 2, 3, 4 ]

console.log(reversed);
// [ 4, 3, 2, 1 ]

--

--

Gerardo Fernández

Entre paseo y paseo con Simba desarrollo en Symfony y React