Array.prototype.with
Returns a copy of an array with one element replaced.
Available since: ES2023
Syntax
array.with(index, value)Parameters
| Parameter | Type | Description |
|---|---|---|
| index | number | The index of the element to replace. A negative one counts from the end. |
| value | any | The new value. |
Return value
ArrayA new array with the element replaced.
Examples
Replacing an element in a copy:
const sizes = ['S', 'M', 'L'];
console.log(sizes.with(1, 'XL').join(', '));
console.log(sizes.join(', '));Output:
S, XL, L
S, M, LReplacing the last element:
console.log([1, 2, 3].with(-1, 30).join(', '));Output:
1, 2, 30Notes
The immutable version of array[index] = value. An index outside the array throws a RangeError.
See also
- Array.prototype.toSpliced — Returns a copy of an array with elements removed, replaced or inserted.
- Array.prototype.at — Returns the element at an index; negative indexes are allowed.
In the tutorial
- Array methods — How to add and remove array elements in JavaScript: push, pop, shift, unshift, slice, splice, concat and join.