DEV Community

Kyle Trahan
Kyle Trahan

Posted on

Mutating vs Non-Mutating JS Arrays

In my last blog post I talked about some mutating methods to manipulate your JS arrays. Such as .push and .unshift. This week I wanted to talk about different ways you can manipulate a JS array using non-mutating methods.

There are two key methods used for adding new items to an array without mutating the original array. They allow you to do something similar to .push/.unshift. The first being the .concat() method. The syntax is very similar to the others.
Lets say we had an array that looked like this:

let numbersArray = [ 1, 2 ,3 ]

and we wanted to add 4 to that array without mutating the original. You could use concat like so:

let numbersArray2 = numbersArray.concat(4)

The original numbersArray would still show as [ 1, 2, 3 ] while our new array would show the 4 added in.

Another way to go about adding elements into an array is to use JS's spread operator. The syntax looks like this:

To add to the end:

let numbersArray2 = [ ...numbersArray, 4 ]

or to add to the beginning:

let numbersArray2 = [ 4, ...numbersArray ]

This takes all of the values from numbersArray and creates a new array with the addition of the number 4 either at the end for the first example or the beginning for the second example.

Let's move on to ways to remove elements from an array without mutating the original. These methods are going to do something similar to .pop/.shift. You could use a method called .filter. This method will sort through an array and create a new one based off of a condition you set. It looks like this:

numbersArray2 = numbersArray.filter( value => value !== 3 )

numbersArray2 would only include [ 1, 2 ] however the original array would remain unchanged.

Another method you can use is called slice. In this method you pass in the parameters of where you want to start your new array and where you want it to end. If you leave the second number out then slice will just go to the last value of the array. Using slice would look like this:

numbersArray2 = numbersArray.slice(0, 2)

So we are saying that we want our numbersArray2 to start at the 0th index and finish on the 1st index. The ending point you pass in to slice is non inclusive, meaning it won't be included in your array. So our numbersArray2 would look like [ 1, 2 ].

I hope this was helpful in understanding a few non-mutating functions with JS arrays. Stay tuned next week I will be going over some functions that iterate over JS arrays. We already saw one in this blog, .filter!

Top comments (0)