Array Mutation vs Non-Mutating Methods
Array Mutation vs Non-Mutating Methods
JavaScript Array methods are strictly categorized into **mutating** (modifying the original array in-place) and **non-mutating** (returning a new array while preserving the original). ES2023 introduced non-mutating counterparts.
The Core Concept
Writing clean, predictable applications requires knowing whether a method mutates in-place. In modern React and state-driven apps, mutation leads to dropped re-renders and stale UI.
// Mutating (In-place)
arr.push(); arr.pop(); arr.shift(); arr.unshift();
arr.splice(); arr.sort(); arr.reverse();
// Non-Mutating (Pure)
arr.slice(); arr.concat(); arr.map(); arr.filter();
// Modern ES2023 Non-Mutating Counterparts:
arr.toSorted(); arr.toReversed(); arr.toSpliced(); arr.with(index, val);Live Interactive Studio
Key Code Patterns in Action
arr.push()
Mutatingconst fruits = ['apple', 'banana'];
// push() appends one or more items to the END of the array in-place
const newLength = fruits.push('cherry', 'date');
console.log("Returned (new length):", newLength); // 4
console.log("Original fruits (mutated):", fruits); // ['apple', 'banana', 'cherry', 'date']arr.pop()
Mutatingconst stack = ['task 1', 'task 2', 'task 3'];
// pop() removes the LAST element from the array in-place
const removedItem = stack.pop();
console.log("Returned (removed item):", removedItem); // 'task 3'
console.log("Original stack (mutated):", stack); // ['task 1', 'task 2']arr.shift()
Mutatingconst queue = ['customer A', 'customer B', 'customer C'];
// shift() removes the FIRST element (index 0) in-place
const served = queue.shift();
console.log("Returned (removed item):", served); // 'customer A'
console.log("Original queue (mutated):", queue); // ['customer B', 'customer C']arr.unshift()
Mutatingconst queue = ['normal task', 'low task'];
// unshift() prepends one or more elements to the BEGINNING (index 0)
const newLength = queue.unshift('URGENT task');
console.log("Returned (new length):", newLength); // 3
console.log("Original queue (mutated):", queue); // ['URGENT task', 'normal task', 'low task']arr.splice()
Mutatingconst items = ['a', 'b', 'c', 'd'];
// splice(start, deleteCount, ...itemsToAdd)
// Removes 2 items starting at index 1, and inserts 'X' & 'Y':
const deleted = items.splice(1, 2, 'X', 'Y');
console.log("Returned (deleted items):", deleted); // ['b', 'c']
console.log("Original items (mutated):", items); // ['a', 'X', 'Y', 'd']arr.sort()
Mutatingconst scores = [40, 10, 100, 25, 5];
// ⚠️ Default sort converts to strings (e.g., '100' comes before '25'):
// scores.sort(); -> [10, 100, 25, 40, 5]
// Proper numeric sort in-place:
scores.sort((a, b) => a - b);
console.log("Original scores (mutated):", scores); // [5, 10, 25, 40, 100]arr.reverse()
Mutatingconst letters = ['a', 'b', 'c', 'd'];
// reverse() inverts element order directly in memory
const returnedRef = letters.reverse();
console.log("Original letters (mutated):", letters); // ['d', 'c', 'b', 'a']
console.log("Returns same array reference?:", returnedRef === letters); // truearr.slice()
Non-Mutatingconst animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
// slice(start, endExclusive) creates a shallow copy of a slice
const extracted = animals.slice(1, 4);
console.log("Returned copy:", extracted); // ['bison', 'camel', 'duck']
console.log("Original animals (pure/intact):", animals); // ['ant', 'bison', 'camel', 'duck', 'elephant']arr.concat()
Non-Mutatingconst teamA = ['Alice', 'Bob'];
const teamB = ['Charlie', 'Dana'];
// concat() joins arrays or values into a brand NEW array
const merged = teamA.concat(teamB, 'Eve');
console.log("Returned merged copy:", merged); // ['Alice', 'Bob', 'Charlie', 'Dana', 'Eve']
console.log("Original teamA (pure/intact):", teamA); // ['Alice', 'Bob']
console.log("Original teamB (pure/intact):", teamB); // ['Charlie', 'Dana']arr.map()
Non-Mutatingconst prices = [10, 20, 30];
// map() transforms each element into a brand NEW array of identical length
const formatted = prices.map((p) => `$${p.toFixed(2)}`);
console.log("Returned new array:", formatted); // ['$10.00', '$20.00', '$30.00']
console.log("Original prices (pure/intact):", prices); // [10, 20, 30]arr.filter()
Non-Mutatingconst numbers = [12, 5, 8, 130, 44];
// filter() creates a NEW array with elements that pass the boolean test
const bigNumbers = numbers.filter((num) => num >= 10);
console.log("Returned new array:", bigNumbers); // [12, 130, 44]
console.log("Original numbers (pure/intact):", numbers); // [12, 5, 8, 130, 44]arr.toSorted()
ES2023 Pureconst scores = [40, 10, 100, 25, 5];
// ES2023 toSorted() sorts into a NEW array without mutating original!
const sortedScores = scores.toSorted((a, b) => a - b);
console.log("Returned sorted copy:", sortedScores); // [5, 10, 25, 40, 100]
console.log("Original scores (pure/intact):", scores); // [40, 10, 100, 25, 5]arr.toReversed()
ES2023 Pureconst items = ['first', 'second', 'third'];
// ES2023 toReversed() returns a REVERSED COPY without mutating original!
const reversed = items.toReversed();
console.log("Returned reversed copy:", reversed); // ['third', 'second', 'first']
console.log("Original items (pure/intact):", items); // ['first', 'second', 'third']arr.toSpliced()
ES2023 Pureconst letters = ['a', 'b', 'c', 'd'];
// ES2023 toSpliced(start, deleteCount, ...itemsToAdd)
// ⚠️ Crucial difference: toSpliced() returns the RESULTING NEW ARRAY,
// whereas splice() mutates original and returns deleted items!
const result = letters.toSpliced(1, 2, 'X', 'Y');
console.log("Returned new array:", result); // ['a', 'X', 'Y', 'd']
console.log("Original letters (pure/intact):", letters); // ['a', 'b', 'c', 'd']arr.with()
ES2023 Pureconst users = ['Alice', 'Bob', 'Charlie'];
// ES2023 with(index, newValue) returns a copy with ONE element replaced:
const updated = users.with(1, 'Bobby');
console.log("Updated copy with(1, 'Bobby'):", updated); // ['Alice', 'Bobby', 'Charlie']
console.log("Original users (pure/intact):", users); // ['Alice', 'Bob', 'Charlie']
// Supports negative index (counts from the end):
const replacedLast = users.with(-1, 'Chuck');
console.log("Replaced last with(-1, 'Chuck'):", replacedLast); // ['Alice', 'Bob', 'Chuck']Real-World Engineering Takeaways
Under the Hood: Engine & Memory Mechanics
Common Pitfalls & Traps
Never mutate state arrays directly in React, Redux, or Vue
// ⚠️ BUG IN REACT:
const [items, setItems] = useState([1, 2, 3]);
items.push(4); // Modifies original array in-place!
setItems(items); // React does Object.is(prev, next) -> SAME REFERENCE! -> NO RE-RENDER!React and modern reactive state frameworks detect changes via shallow reference equality. Because mutating methods modify the existing array at the same heap address, the reference is identical and re-rendering is skipped. Always use non-mutating methods (toSorted, toSpliced, with, filter, map) or spread clones `[...items, 4]`.
Beware: splice() returns deleted items, but toSpliced() returns the new array
const arr = [1, 2, 3];
const res1 = arr.splice(1, 1); // res1 is [2] (the deleted items) ⚠️
const res2 = arr.toSpliced(1, 1); // res2 is [1, 3] (the resulting array) ✅This is one of the most common API signature traps in modern JavaScript. In-place `splice()` returns what was removed, whereas pure `toSpliced()` returns the newly constructed array with modifications applied.
Quick Knowledge Check
Test your understanding on these 10 questions (one by one):
What is the core purpose of Array Mutation vs Non-Mutating Methods in JavaScript?
// Concept 22: Array Mutation vs Non-Mutating Methods
// Understanding the core mental model