Array. prototype. with()
Returns a copy of the array in which the element at the given index has a new value.
- Returns
- A new array with the element replaced.
- Changes the original
- No
Example
#const scores = [70, 85, 90]
const corrected = scores.with(1, 95)
console.log(corrected)
console.log(scores)
console.log(scores.with(-1, 100))Definition and usage
#The with(index, value) method is the non-mutating counterpart to the assignment array[index] = value. It makes a copy of the array, replaces one element in it, and returns the result. The original is left untouched.
It supports negative indexes, just like at(): with(-1, x) changes the copy’s last element. An out-of-range index doesn’t extend the array; instead it throws a RangeError, which protects against accidentally creating holes.
It belongs to the family of copying methods, together with toSorted(), toReversed(), and toSpliced(). It’s most useful where data needs to stay immutable: in React component state, in Redux reducers, or in an undo history.
Syntax
#array.with(index, value)Parameters
#index
integer
The position of the element to replace. Negative values count from the end.value
any value
The element’s new value.
More examples
#const days = ['mon', 'tue', 'wed']
try {
days.with(5, 'sat')
} catch (error) {
console.log(error.name)
}
const copy = [...days]
copy[5] = 'sat'
console.log(copy.length)A plain assignment to index 5 stretched the copy out to six elements and left holes in it. with() throws an error in that situation instead.
const todos = [
{ title: 'HTML quiz', done: false },
{ title: 'CSS project', done: false }
]
const updated = todos.with(0, { ...todos[0], done: true })
console.log(updated[0])
console.log(todos[0])Browser support
#Widely available · since 2023
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- To change one field of an object in an array, combine
with()with a spread:list.with(i, { ...list[i], done: true }). - Don’t call
with()in a loop to change several elements. Each call copies the whole array, so a singlemap()is better.
Related entries
#- Array.prototype.at()Returns the element at the given index, which can also be counted from the end.
- Array.prototype.toReversed()Returns a new array with the elements in reverse order, without changing the original.
- Array.prototype.toSpliced()Removes, inserts, or replaces elements in a copy of the array. The original is left unchanged.
- Array.prototype.map()Creates a new array with the results of calling a function for every element.
- Spread (...)The spread syntax spreads an array, string, or object out into individual elements: for copying, merging, and passing arguments.
Spotted a mistake or missing an example? Write to us.