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 arraypop()— removes the last elementshift()— removes the first elementunshift()— adds an element to the beginningsplice()— 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 functionfilter()— returns a new array with elements that pass the testslice()— returns a copy of a portion of the arrayconcat()— 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.