Skip to content
The Weekly Dev

Brussels Software Studio & Technology Publication

Est. 2022  ·  Vol. I
The Weekly Dev

New Array Methods Coming to JavaScript

JavaScript stores objects and arrays in heap storage, meaning any updates will mutate the original. New immutable array methods — toReversed, toSorted, toSpliced, and with — solve this cleanly.

VA

By Vassilios Zalimidis ·

About arrays and their mutations

As we know, JavaScript stores objects and arrays in heap storage. That means any updates to an array will mutate the original:

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 create copies of arrays using the spread operator:

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, four new immutable methods are being added to JavaScript.

New Change Array by Copy methods

  • Array.prototype.toReversed() — Clones an array, then reverses it.
  • Array.prototype.toSorted(compareFn) — Clones an array, then sorts it.
  • Array.prototype.toSpliced(start, deleteCount, ...items) — Clones an array, then splices it.
  • Array.prototype.with(index, value) — Clones an array, then replaces an element at the given index.

toReversed()

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

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

toSorted()

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

You can also pass a comparison function, just like sort():

let arrayA = [{ value: 1 }, { value: 5 }, { value: 3 }];
let arrayB = arrayA.toSorted((a, b) => a.value - b.value);
// [{ value: 1 }, { value: 3 }, { value: 5 }]

toSpliced()

let x = ["Car", "Bike", "Scooter", "Motorcycle"];

let y = x.toSpliced(1, 2, "Train"); // ["Car", "Train", "Motorcycle"]
let z = x.toSpliced(1, 3);          // ["Car"]

with()

let x = ["Car", "Bike", "Scooter"];

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

Conclusion

This is a very welcome addition to JavaScript. With these new methods, the complexity of keeping the original array untouched is removed and the readability of the code improves significantly.