Replacing .splice() with Spread and Slice
You'll learn how to perform .splice() operations immutably by combining slice and the spread operator.
While .splice() is powerful, it mutates the original array. When you need to insert, remove, or replace elements at any position without mutation, you can combine .slice() with the spread operator (...) to achieve the same results immutably.
The Core Pattern
Think of your array like a sandwich. To add or remove ingredients from the middle, you:
- Cut the sandwich before the target spot (first slice)
- Make your changes
- Reattach everything after the target spot (second slice)
Removing elements immutably:
const numbers = [1, 2, 3, 4, 5];
// Mutating way: numbers.splice(2, 2)
const removed = [
...numbers.slice(0, 2), // Everything before index 2
...numbers.slice(4) // Everything after the removed section
];
console.log(removed); // [1, 2, 5]
console.log(numbers); // [1, 2, 3, 4, 5] — original unchanged!
Inserting elements immutably:
const colors = ['red', 'blue'];
// Mutating way: colors.splice(1, 0, 'yellow', 'green')
const inserted = [
...colors.slice(0, 1), // Before insertion point
'yellow', 'green', // New elements
...colors.slice(1) // After insertion point
];
console.log(inserted); // ['red', 'yellow', 'green', 'blue']
Replacing elements immutably:
const fruits = ['apple', 'banana', 'cherry', 'date'];
// Replace 'banana' and 'cherry' with 'orange'
const replaced = [
...fruits.slice(0, 1), // Before replacements
'orange', // New value
...fruits.slice(3) // After replacements
];
console.log(replaced); // ['apple', 'orange', 'date']
Key Takeaway: Use ...array.slice(0, index) for "everything before," your changes in the middle, and ...array.slice(endIndex) for "everything after" to immutably replicate any .splice() operation.