JavaScriptArrays

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
On this page

Example

#
JavaScript
const scores = [70, 85, 90]
const corrected = scores.with(1, 95)

console.log(corrected)
console.log(scores)
console.log(scores.with(-1, 100))
Console
[70, 95, 90]
[70, 85, 90]
[70, 85, 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

#
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

#
An out-of-range index
JavaScript
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)
Console
RangeError
6

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.

Updating a task without mutation
JavaScript
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])
Console
{ title: 'HTML quiz', done: true }
{ title: 'HTML quiz', done: false }

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 single map() is better.

Related entries

#

Spotted a mistake or missing an example? Write to us.