Example 1 — Replace an Index
Swap one element and keep a new array.
const fruits = ["apple", "orange", "banana", "grape"];
const updated = fruits.with(2, "pineapple");
console.log(updated);
console.log(fruits[2]); // still "banana" How It Works
- Start with fruits. Index 2 is
"banana". - Call with(2, "pineapple"). Builds a new array with that slot replaced.
- updated has pineapple. The copy reflects the change.
- Original stays.
fruits[2]is still"banana".

