Immutable Array Updates: Replacing Elements
You'll learn how to replace specific array elements without mutating the original array.
The Core Idea
When working with immutable patterns, you can't simply write arr[2] = newValue because that directly mutates the array. Instead, you need to create a new array with the replacement applied. Think of it like editing a document by making a fresh copy with your changes, rather than erasing the original.
Techniques for Immutable Replacement
Using map()
The map() method is perfect when you want to replace elements based on their index or value:
const numbers = [10, 20, 30, 40];
// Replace the element at index 2
const updated = numbers.map((num, index) =>
index === 2 ? 999 : num
);
console.log(updated); // [10, 20, 999, 40]
console.log(numbers); // [10, 20, 30, 40] (unchanged)
Using Spread Syntax
For single-index replacements, you can slice around the target index and spread the pieces together:
const colors = ['red', 'green', 'blue'];
// Replace index 1
const replaced = [
...colors.slice(0, 1),
'yellow',
...colors.slice(2)
];
console.log(replaced); // ['red', 'yellow', 'blue']
console.log(colors); // ['red', 'green', 'blue'] (unchanged)
Practical Example
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
// Replace the user with id 2
const updatedUsers = users.map(user =>
user.id === 2 ? { ...user, name: 'Robert' } : user
);
Key Takeaway: Use map() with conditional logic or spread with slice() to replace array elements immutably—the original array stays untouched while you create a new version with your changes.