Skip to content
Concept 22 // Module 03: Data Structures & Programming Fundamentals

Array Mutation vs Non-Mutating Methods

Module 03: Data Structures & Programming Fundamentals•Concept 22 of 100• 5 min read

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.

Syntax Reference
// 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

`push()` appends one or more elements to the end of the original array and mutates it in-place. Crucially, it returns the *new length* of the array, NOT the array itself.
JavaScript Editor
Loading...
Console Output
Waiting for output...

Key Code Patterns in Action

01

arr.push()

Mutating
const 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']
`push()` appends one or more elements to the end of the original array and mutates it in-place. Crucially, it returns the *new length* of the array, NOT the array itself.
02

arr.pop()

Mutating
const 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']
`pop()` removes the last element from an array in-place and returns that element. If the array is already empty, it returns `undefined` without throwing an error.
03

arr.shift()

Mutating
const 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']
`shift()` removes the element at index 0 and shifts all remaining elements down by one index. It mutates the array in-place with O(N) linear time complexity and returns the removed element.
04

arr.unshift()

Mutating
const 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']
`unshift()` inserts one or more items at the beginning of the array in-place, shifting existing items forward. Like `push()`, it returns the *new array length*.
05

arr.splice()

Mutating
const 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']
`splice()` is the Swiss Army knife for in-place array modification. It can remove, insert, or replace elements at any index. It mutates the original array and returns an array of the deleted elements.
06

arr.sort()

Mutating
const 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]
`sort()` reorders array elements in-place and returns the same array reference. Always provide a comparator function `(a, b) => a - b` when sorting numbers to avoid lexicographical string sorting bugs.
07

arr.reverse()

Mutating
const 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); // true
`reverse()` flips the array elements in-place. The first becomes the last, and the last becomes the first. It mutates the array and returns the mutated array reference itself.
08

arr.slice()

Non-Mutating
const 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']
`slice()` extracts a section of an array and returns a brand-new array. The original array is left completely untouched (non-mutating).
09

arr.concat()

Non-Mutating
const 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']
`concat()` merges two or more arrays (or values) and returns a new combined array. None of the original input arrays are altered.
10

arr.map()

Non-Mutating
const 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]
`map()` calls a transformer callback on each element and returns a newly constructed array containing the returned values, preserving the original array.
11

arr.filter()

Non-Mutating
const 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]
`filter()` iterates through each element and evaluates a predicate function. It returns a new array with all elements that return a truthy value without mutating the source array.
12

arr.toSorted()

ES2023 Pure
const 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]
Introduced in ES2023, `toSorted()` provides the immutable counterpart to `sort()`. It returns a sorted copy of the elements, keeping the source array intact.
13

arr.toReversed()

ES2023 Pure
const 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']
Introduced in ES2023, `toReversed()` is the immutable twin of `reverse()`. It produces a new array with items in reverse order while preserving the original array.
14

arr.toSpliced()

ES2023 Pure
const 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']
Introduced in ES2023, `toSpliced()` performs slice-and-splice operations without mutating the original array. Note that `toSpliced()` returns the new modified array, whereas `splice()` returns the deleted items.
15

arr.with()

ES2023 Pure
const 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']
Introduced in ES2023, `arr.with(index, value)` replaces the value at the given index immutably, returning a new array. Negative indices count backward from the end (-1 is the last item).

Real-World Engineering Takeaways

React State Updates: Using `toSorted()` or `filter()` instead of mutating state arrays.
Data Pipelines: Chaining non-mutating transforms `arr.filter().toSorted().map()` safely.
Performance Optimization: Using in-place `splice()` or `push()` inside tight computational loops where memory allocation is critical.

Under the Hood: Engine & Memory Mechanics

How JavaScript Executes This
Mutating methods modify the backing storage vector in-place. Non-mutating methods allocate a new ArrayBuffer vector on the heap and copy the element pointers.

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):

Score: 0 / 10
Question 1 of 10 • Core Purpose & Mental Model

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
1 / 10