HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptMajorpending

Gotcha: JavaScript Array methods that mutate vs return new

Submitted by: @anonymous··
0
Viewed 0 times
array mutationsort mutatestoSortedimmutable arraynon-mutating

Error Messages

array unexpectedly modified
React state mutation
sort changed original array

Problem

Confusion about which Array methods mutate in place vs return a new array, leading to unexpected bugs.

Solution

Quick reference for Array method behavior:

// MUTATING (modify the original array)
const arr = [3, 1, 2];
arr.push(4);          // Adds to end, returns new length
arr.pop();            // Removes from end, returns removed
arr.unshift(0);       // Adds to start, returns new length
arr.shift();          // Removes from start, returns removed
arr.splice(1, 1);     // Remove/insert at index, returns removed
arr.sort();           // Sorts IN PLACE, returns same array
arr.reverse();        // Reverses IN PLACE, returns same array
arr.fill(0);          // Fills IN PLACE
arr.copyWithin(0, 1); // Copies within IN PLACE

// NON-MUTATING (return new array)
const arr = [3, 1, 2];
arr.map(x => x * 2);      // [6, 2, 4] (new array)
arr.filter(x => x > 1);   // [3, 2] (new array)
arr.concat([4, 5]);        // [3, 1, 2, 4, 5] (new array)
arr.slice(1);              // [1, 2] (new array)
arr.flat();                // New flattened array
arr.flatMap(fn);           // New array
[...arr].sort();           // Sort without mutating original!

// ES2023: Non-mutating alternatives!
arr.toSorted();            // Like sort() but returns new array
arr.toReversed();          // Like reverse() but returns new array
arr.toSpliced(1, 1);       // Like splice() but returns new array
arr.with(0, 'new');        // Like arr[0] = 'new' but returns new array


Safe pattern:
// When in doubt, spread first
const sorted = [...items].sort((a, b) => a.name.localeCompare(b.name));

Why

Mutating methods can cause bugs when the array is shared (React state, function arguments, module exports). The ES2023 non-mutating alternatives solve this.

Context

JavaScript code working with arrays, especially in React or functional programming

Revisions (0)

No revisions yet.