Array.prototype.with()
The non-mutating form of arr[i] = value. Unlike bracket assignment it refuses an out-of-range index instead of quietly creating a hole or a stray property.
Demo
One element is replaced and everything else is copied through, leaving the source untouched. Negative indices count from the end, exactly like at(). The last case is what distinguishes this from bracket assignment: an index outside the array throws a RangeError rather than silently extending the array with a hole — which is what arr[99] = 9 would have done.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| index | number | yes | Position to replace. Negative counts from the end. Anything outside the array throws RangeError. |
| value | any | yes | The replacement value for that position. |
Return value
Array — A NEW array identical to the original except at one index. Throws RangeError if the index is out of bounds.
Common patterns
setItems(items.with(index, updated));
const next = items.with(-1, replacement);
const next = items.map((x, j) => j === i ? value : x);
Examples
Pitfalls
[1, 2, 3].with(99, 0)
if (i >= 0 && i < items.length) items.with(i, v);
[1, 2, 3].with(1, 9)
[1, 2, 3].toSpliced(1, 0, 9)
items.with(0, 1)
items.map((x, j) => j === 0 ? 1 : x)
When to use
- Replacing a single element in state or props
- Updating by index inside an expression
- Anywhere a map comparing indices is used just to swap one value
- Adding or removing elements → toSpliced
- You own the array and want it changed in place → arr[i] = value
- The index may be out of range → bounds-check, or it throws
- Runtimes older than ES2023 → map with an index comparison
Notes
FAQ
Because bracket assignment on an array is really property assignment — arr[99] = 0 on a three-element array just sets a property and stretches the length to 100, leaving holes. with() is specified to reject an index outside the current bounds, which catches the mistake instead of producing a sparse array.
const a = [1]; a[99] = 0; a.length; // 100, with holes a.with(99, 0); // RangeError