New array methods coming in JavaScript

Created: Nov 29th 2022 - Updated : Nov 30th 2022

About Arrays and their mutations

As we know, JavaScript stores objects and arrays in heap storage. That means the memory assigned for a specific array / object is dynamic and once the array has been created. And we don't always want this.

ArrayMethods.js
let demoArray = [ 'a', 'b', 'c'];
let newArray = demoArray;

newArray[0] = 'd';

console.log(demoArray); // ['d', 'b', 'c']
console.log(newArray); // ['d', 'b', 'c']

Because of that, we often find ourselves creating copies of the arrays to apply our changes without mutating the original. This is usually done with the spread (three dots) operator

SpreadOperator.js

const numbersArray = [1, 2, 3];
let numbersArrayCopy = [...numbersArray];

numbersArrayCopy[0] = 5;
console.log(numbersArray) // [1, 2, 3]
console.log(numbersArrayCopy) // [5, 2, 3]

Since cloning arrays is so common when we want to keep the original immutable, a new specification reached stage 3.

The following proposal, is what introduces these methods and I'm pretty sure everyone will welcome them with excitement. Read more regarding the "Change Array by copy"

If you want to check this out, here is a polyfill that recreates the proposal's behaviour.

New Change Array by Copy methods

The proposal adds 4 new methods which will copy an array and then apply the changes. These methods are the following :

  • Array.prototype.toReversed() - Clones an array, and then reverses it.
  • Array.prototype.toSorted(compareFn) - Clones an array, and then sorts it.
  • Array.prototype.toSpliced(start, deleteCount, ...items) - Clones an array, and splices it in some way
  • *Array.prototype.with(index, value) - Clones an array, and adds a new element in the index you provide
toReversed()

toReversed() does exactly what it says. It clones an array, and reverses the order of the values in it. Since this method clones the array, we don't need to do any manual copy of the original to create a new version :

toReversed.js
let arrayA = [ 'a', 'b', 'c' ];
let arrayB = arrayA.toReversed();

console.log(arrayA, arrayB); // Returns [ 'a', 'b', 'c'], [ 'c', 'b', 'a' ]
toSorted()

toSorted() is the immutable version of sort(), meaning it will not mutate (alter) the original array. It will clone it instead and sort it (numerically by default) :

toSorted.js
let x = [ 5, 1, 2, 4, 3];
let y = x.toSorted(); // returns [ 1, 2, 3, 4, 5 ]

You can also use a comparison method exactly like the sort() method in JavaScript, and it is really useful when we want to sort an array of objects :

toSortedObjectArray.js
let arrayA = [
    { value: 1 },
    { value: 5 },
    { value: 3 },
    { value: 4 },
    { value: 2 }
];


let arrayB = arrayA.toSorted((a, b) => {
    return a.value - b.value
});

console.log(arrayB);
// [
//	  { value: 1 },
//    { value: 2 },
//    { value: 3 },
//    { value: 4 },
//    { value: 5 }
// ]
toSpliced()

toSpliced() is the immutable version of splice(). It doesn't alter the original array and accepts 3 arguments:

  • start - the position to start at.
  • deleteCount - the number of elements to remove.
  • ...items - any items to insert at index after deletion.
toSpliced.js
let x = [ "Car", "Bike", "Scooter", "Motorcycle", "RollerBlades", "Skateboard" ];


let y = x.toSpliced(1, 2, "Train"); //y=[ "Car", "Train", "Bat",  "Motorcycle", "RollerBlades", "Skateboard" ]


let z = x.toSpliced(1, 3); // z=[ "Car", "RollerBlades", "Skateboard" ]

as you can see, this is an example of how useful these new methods are. The original array would've been mutated had we used the sort() method, but with toSpliced() we can use the original array as many times, without worrying about altering it.

with()

Last, we have with(), which takes an array, and returns a clone of it "with" a something we declare :

with.js
let x = [ "Car", "Bike", "Scooter" ];

let y = x.with(1, "Train"); // y=["Car", "Train", "Scooter"]

let z = x.with(0, "Skateboard"); // z=["Scateboard", "Bike", "Scooter"]

Conclusion

This is a very welcome addition to JavaScript. It was needed, since JavaScript maintains only one copy of the an object or an array. With these new methods, the complexity of keeping the the original array untouched ir removed and the readability of the code improves a lot.