References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript array.with() method

Method JavaScript All modern browsers Updated
Quick answer

The with() method returns a new array with the element at one index replaced, leaving the original unchanged. arr.with(1, "x") returns a copy where index 1 is "x". It's the non-mutating version of arr[1] = "x", and it accepts negative indices.

Overview

with() changes a single element by index — without mutating. Where arr[1] = "x" modifies the array in place, arr.with(1, "x") returns a new array with that one element replaced and leaves the original untouched. It even accepts negative indices, so arr.with(-1, "x") replaces the last element.

It's built for immutable updates, which are everywhere in modern state management. Updating one item in a list without mutating the source array used to require [...arr] then an assignment, or a map() with an index check; with() does it in one readable call: const next = todos.with(i, { ...todos[i], done: true }).

It rounds out the non-mutating array family with toSorted(), toReversed() and toSpliced() — together they cover replace, sort, reverse and splice without ever changing the original. An out-of-range index throws a RangeError. Support is solid in current browsers.

Syntax

const updated = array.with(index, value)

[1, 2, 3].with(1, 9)     // [1, 9, 3]  (original unchanged)
[1, 2, 3].with(-1, 9)    // [1, 2, 9]  (negative index)

Parameters

The array.with() method accepts the following parameters.

Parameter Description
index The index to change. Negative counts from the end. Out of range throws a RangeError.
value The new value for that index.

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const scores = [10, 20, 30];

  const updated = scores.with(1, 99);

  document.getElementById('out').textContent =
    'updated:  ' + updated.join(', ') + '\n' +
    'original: ' + scores.join(', '); // updated: 10, 99, 30 / original: 10, 20, 30
</script>

Best practices

  • Use with() to replace one element immutably instead of [...arr] + assignment.
  • Combine with the spread to update an object in a list: arr.with(i, { ...arr[i], done: true }).
  • Use negative indices to target from the end.
  • Pair it with toSorted(), toReversed() and toSpliced() for non-mutating edits.

Frequently asked questions

What does array.with() do?
It returns a copy of the array with the element at the given index replaced, without changing the original.
How do I update one array item without mutating?
Use arr.with(index, newValue), which returns a new array with that index changed.
Does with() support negative indices?
Yes — arr.with(-1, value) replaces the last element. An out-of-range index throws a RangeError.
How is with() different from arr[i] = value?
Bracket assignment mutates the array in place; with() returns a new array and leaves the original unchanged.