DEV Community

Cover image for Array Mutation Methods in JavaScript
Richard Torres
Richard Torres

Posted on

Array Mutation Methods in JavaScript

Introduction

Mutating is the concept of changing the assignment of a value in Javascript.

const fruits = ['apple', 'banana', 'cherry']; // arr = ['apple', 'banana', 'cherry']
fruits.push('date'); // arr = ['apple', 'banana', 'cherry', 'date']
Enter fullscreen mode Exit fullscreen mode

Certain array methods in Javascript mutate the original array. This may lead to unintended consequences in your code if you're not cautious when using such methods.

const fruits = ['apple', 'banana', 'cherry']; // arr = ['apple', 'banana', 'cherry']
const newFruits = arr.push('date'); // arr = ['apple', 'banana', 'cherry', 'date']
Enter fullscreen mode Exit fullscreen mode

In the example above, newFruits is intended to be a copy of fruits with the value of dates added, however the push method mutates the original array, leading to fruits being mutated and the newFruits assignment likely being redundant.

Mutation is not inherently bad; there are times in which we likely want to mutate an array without keeping a reference to the original array.

const flowers = ['lilac', 'daisy', 'rose']
flowers.sort();
Enter fullscreen mode Exit fullscreen mode

In the example above, you can imagine a list of flowers a user is adding in no particular order but would like to see in alphabetical order. We don't care to store the unsorted list in this scenario, so we can mutate the original array.

Mutating Methods

The following is a list of methods that mutate an array:

  1. copyWithin: Copies part of the array to another location in the same array
  2. fill: Changes all elements within a range in an array to a static value
  3. pop: Removes the last element from an array
  4. push: Adds the specified elements to the end of an array
  5. reverse: Reverses an array
  6. shift: Removes the first element from an array
  7. sort: Sorts an array
  8. splice: Removes or replaces existing elements and/or adds new elements
  9. unshift: Adds the specified elements to the beginning of an array

In general, methods that mutate change the array's length or the values at particular indices of the array.

Resources

Does it Mutate is an excellent resource which lists array methods in JavaScript, provides, examples, and classifies each one as "mutates" or "no mutation".

mdn web docs provides a comparison table of mutating methods and their non-mutating alternative, if one exists.

Conclusion

While the concept of mutation of arrays in JavaScript warrants merit, often it can lead to error-prone code if an array-mutating method is used unintentionally. If you're finding that values in your arrays in your code are inexplicably changing, you may have an array-mutating method in use. It's worthwhile investigating, and if find this is your case, set up testing around this functionality to prevent regression.

Top comments (0)