DEV Community

Cover image for New array methods in JavaScript bring immutability
Christian Heilmann
Christian Heilmann

Posted on

11 1

New array methods in JavaScript bring immutability

JavaScript now has a way to change elements, sort, reverse and splice arrays without changing the original, thus giving it immutability. The new methods are with(), toSorted(), toReversed() and toSpliced(). No need to create a copy with [...arr] first. Only missing support is Firefox.

const arr = ['f','c','k','a','f','d'];

const newArr = arr.with(2,'m');
// newArr -> ['f', 'c', 'm', 'a', 'f', 'd']
const sortArr = arr.toSorted();
// sortArr -> ['a', 'c', 'd', 'f', 'f', 'k']
const reverseArr = arr.toReversed();
// reverseArr -> ['d', 'f', 'a', 'k', 'c', 'f']
const splicedArr = arr.toSpliced(3, 3, 'it');
// splicedArr -> ['f', 'c', 'k', 'it']
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

Learn how to monitor AWS container environments at scale

In this eBook, Datadog and AWS share insights into the changing state of containers in the cloud and explore why orchestration technologies are an essential part of managing ever-changing containerized workloads.

Download the eBook

Top comments (4)

Collapse
 
femincan profile image
Furkan Emin Can β€’ β€’ Edited

Thank you for the helpful information!

I particularly like the with method the most. The only drawback is that it isn't currently compatible with Firefox. I hope it becomes available soon

Collapse
 
maxart2501 profile image
Massimo Artizzu β€’

Fortunately, they can be easily polyfilled.

Collapse
 
panayiotisgeorgiou profile image
Panayiotis Georgiou β€’

thanks for the useful information..

Collapse
 
toddpress profile image
Todd Pressley β€’

to quote the last will and testament of the spliced array, ['f', 'c', 'k', 'it']