Sobes.tech
Middle+

What is a mutation and mutating array methods in JavaScript? Provide examples of mutating and non-mutating methods.

sobes.tech AI

Answer from AI

Mutation in JavaScript is a change to the original array or object. Mutating array methods modify the array itself, while non-mutating methods return a new array, leaving the original unchanged.

Examples of mutating methods:

  • push() — adds an element to the end of the array
  • pop() — removes the last element
  • shift() — removes the first element
  • unshift() — adds an element to the beginning
  • splice() — adds/removes elements by index
let arr = [1, 2, 3];
arr.push(4); // arr is now [1, 2, 3, 4]
arr.splice(1, 1); // removes the element at index 1, arr is now [1, 3, 4]

Examples of non-mutating methods:

  • map() — returns a new array transformed by a function
  • filter() — returns a new array with elements that pass the test
  • slice() — returns a copy of a portion of the array
  • concat() — joins arrays, returning a new one
let arr = [1, 2, 3];
let newArr = arr.map(x => x * 2); // newArr is [2, 4, 6], arr remains unchanged
let filtered = arr.filter(x => x > 1); // filtered is [2, 3]

Understanding the difference is important for managing state and preventing unexpected side effects in your code.

What is a mutation and mutating array methods in… - sobes.tech