DEV Community

Abbey Bercher
Abbey Bercher

Posted on

Array Methods — Destructive vs Nondestructive

Working with data is a fundamental aspect of JavaScript. During my first phase at Flatiron School, I found myself using array methods in everything I did. Array methods could be pretty difficult to use, considering there were so many to work with, and they all did different things. There’s many ways we can group these methods, such as arguments and return value.
When working with arrays, we have to be careful and aware of which methods are destructive and which are nondestructive. Destructive methods are methods that return a mutated or altered array, and nondestructive methods return a new array.
Below we can see that after we use .push() on our array, we alter that array. This is destructive.

code snippet

Below you can see that the spread operator can be used to make a copy of and avoid altering the original array. This is nondestructive.

code snippet

When should we use a nondestructive method over a destructive method?
We can use a nondestructive method when we want to preserve the data from the original array.
Which methods are destructive?
Destructive methods include .push(), .unshift(), .pop(), .shift(), and .splice()
Which methods are nondestructive?
Nondestructive methods include spread operator […] and .slice()
Summary
Be careful when working with arrays to ensure you don’t mutate data that you want to preserve.

Top comments (0)