Array.prototype.with()
Returns a new array with the element at a given index replaced, without mutating the original.
Syntax
arr.with(index, value) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
index | number | Yes | Index of the element to replace. Negative counts from the end. |
value | any | Yes | The new value to place at the index. |
Returns
Array — A new array with the element replaced.
Throws
RangeError— the index is out of bounds.
Examples
const a = [1, 2, 3];
console.log(a.with(1, 9), a);
Output
[ 1, 9, 3 ] [ 1, 2, 3 ]
console.log([1, 2, 3].with(-1, 0));
Output
[ 1, 2, 0 ]
Notes
Non-mutating counterpart to bracket assignment. Throws RangeError for an
out-of-bounds index (unlike `arr[i] = v`). Always returns a new array.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 110 |
| firefox | 115 |
| safari | 16 |
| edge | 110 |
| node | 20 |