Mutable and Immutable Array Methods in JavaScript
Mutable and Immutable Array Methods in JavaScript — What's the Difference?
In JavaScript, array methods can be divided into two categories:
Understanding this distinction is critical when writing predictable, maintainable code or working with state management, such as in React.
When you pass an array into a function, it is passed by reference (not copied). This means mutable methods can unintentionally alter the array in other parts of your code.
const arr = [1, 2, 3]; const result = arr.reverse(); // MUTABLE console.log(arr); // [3, 2, 1] console.log(result); // [3, 2, 1]
Method | Description |
map | Returns a new array with modified values |
filter | Filters the array and returns a new one |
slice | Returns a portion of the array as a new copy |
concat | Combines arrays without modifying the original |
flat, flatMap | Flattens arrays but leaves the original unchanged |
toSorted, toReversed, toSpliced | New ES2023 immutable alternatives |
const arr = [1, 2, 3]; const doubled = arr.map(x => x * 2); // [2, 4, 6] console.log(arr); // [1, 2, 3] console.log(doubled); // [2, 4, 6]
Method | Description |
push | Adds an element to the end |
pop | Removes the last element |
shift | Removes the first element |
unshift | Adds elements to the beginning |
splice | Adds/removes elements in place |
sort | Sorts the array in place |
reverse | Reverses the array in place |
const arr = [1, 2, 3]; arr.push(4); // arr = [1, 2, 3, 4]
Starting with ES2023 (ES14), JavaScript includes new immutable versions of common operations.
New Method | Purpose |
toSorted() | Immutable version of sort() |
toReversed() | Immutable version of reverse() |
toSpliced() | Immutable version of splice() |
const arr = [3, 1, 2]; const sorted = arr.toSorted(); // [1, 2, 3] console.log(arr); // [3, 1, 2]
In React, state should never be mutated directly. This is why immutable methods are preferred. For example:
// Bad: state.numbers.push(4); // Good: setState(prev => ({ numbers: [...prev.numbers, 4] }));