with() for Immutable Index Updates
You'll learn how to create a modified copy of an array with one element changed, without mutating the original.
When you need to update a single element in an array but want to preserve the original (immutability), the with() method is your friend. It returns a new array identical to the original except for one changed element at a specified index.
How with() Works
The with() method takes two arguments: the index you want to update and the new value for that position. It creates a fresh array, leaving the original untouched.
const fruits = ['apple', 'banana', 'cherry'];
const updated = fruits.with(1, 'blueberry');
console.log(updated); // ['apple', 'blueberry', 'cherry']
console.log(fruits); // ['apple', 'banana', 'cherry'] — unchanged!
Think of it like making a photocopy of a list, but changing one word on the copy. Your original list stays pristine.
Why Use with() Instead of Mutation?
Compare this to direct assignment, which mutates:
const nums = [10, 20, 30];
nums[1] = 25; // mutates the original
console.log(nums); // [10, 25, 30]
With with(), you get a new array, which is safer when working with state in modern frameworks or when you need to preserve history.
Negative Indices
Just like slice(), with() supports negative indices to count from the end:
const letters = ['a', 'b', 'c'];
const result = letters.with(-1, 'z');
console.log(result); // ['a', 'b', 'z']
Key Takeaway: Use with() to create a new array with a single element changed at a given index, keeping your original array completely untouched—perfect for immutable updates.