Updating one item in a list without mutating it used to mean a copy first: const copy = [...arr]; copy[2] = x;. Two lines for one change. Array.prototype.with() does it as one expression. I’d rather read one line than a copy-then-assign pair.
It returns a new array with the item at the given index replaced and leaves the original alone:
const arr = [1, 2, 3, 4, 5];
arr.with(2, 6); // [1, 2, 6, 4, 5]
arr; // [1, 2, 3, 4, 5], untouched
arr.with(-1, 10); // [1, 2, 3, 4, 10]
Negative indexes count from the end, like at(). Because it returns an array you can chain it, which is where it shines in state updates for UI code where mutating state is a bug:
const next = todos.with(index, { ...todos[index], done: true });
It belongs to the same family as toSorted(), toReversed() and toSpliced(): the copying versions of methods that normally change the array in place.
Two caveats. First, an index outside the array throws a RangeError instead of quietly growing the array like arr[10] = 0 would:
[1, 2, 3].with(10, 0); // RangeError
Second, the result is always a dense array, so empty slots in a sparse array become undefined. The copy is also shallow, so objects inside are still shared with the original, which is why the todo example above spreads the object.
It has been in all major browsers since July 2023. For older targets you need a transpiler or a fallback.
Further reading: MDN: Array.prototype.with()