Mutating and Non-Mutating Array Methods in JavaScript
Array Methods in JavaScript
JavaScript provides a powerful set of methods for working with arrays. They all divide into mutating (modify original array) and non-mutating (return new array or value without touching original).
Mutating Array Methods
These methods modify the array itself:
| Method | Description |
|---|---|
push() | Adds element to end |
pop() | Removes last element |
shift() | Removes first element |
unshift() | Adds element to beginning |
splice() | Removes, replaces or inserts elements by index |
sort() | Sorts array (default as strings, can pass comparison function) |
reverse() | Reverses element order |
fill() | Fills array with specific value |
copyWithin() | Copies elements within array |
splice() Example
const arr = [1, 2, 3, 4];
arr.splice(1, 2); // Removes 2 elements from index 1
console.log(arr); // [1, 4]
Non-Mutating Array Methods
These methods don't modify original array, but return new value:
| Method | Description |
|---|---|
slice() | Returns subarray |
concat() | Combines arrays |
map() | Creates new array applying function to each element |
filter() | Filters elements by condition |
find() | Returns first element matching condition |
findIndex() | Returns index of first matching element |
every() | Checks if all elements satisfy condition |
some() | Checks if at least one element satisfies condition |
reduce() | Transforms array into single value |
includes() | Checks value presence |
indexOf() | Returns index of first match |
lastIndexOf() | Returns index of last match |
flat() | "Flattens" nested arrays |
join() | Converts array to string |
toSorted() | New way to sort without array mutation (ES2023) |
toReversed() | Returns new array with reversed element order without mutating original (ES2023) |
toSpliced() | Returns new array with removed/replaced elements without mutating original (ES2023) |
map() Example
const nums = [1, 2, 3];
const doubled = nums.map(n => n * 2);
console.log(doubled); // [2, 4, 6]
Important:
Methods sort(), reverse(), splice() modify original array. If you want to preserve original, use non-mutating alternatives from ES2023: toSorted(), toReversed(), toSpliced(), or make a copy first: const sorted = [...array].sort()
Conclusion
- Use mutating methods consciously when array modification is acceptable.
- Prefer non-mutating methods when you need to preserve original.