Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Array

Array.prototype.with()

Reference for JavaScript Array.prototype.with(): return a copy of an array with one element replaced, using negative indexes, without changing the original.

The with() method returns a copy of an array in which the element at one index has been replaced. The original array is not touched. It is the non-mutating version of assigning with brackets: arr[i] = value.

Because it returns a new array, you can chain it with other copying methods, and you can use it in places where a statement like arr[i] = x is not allowed, such as inside an expression or an arrow function body.

JavaScript
const scores = [10, 20, 30];
const updated = scores.with(1, 99);
// updated is [10, 99, 30], scores is still [10, 20, 30]

Try it

JS Replace one element

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Out of range and chaining

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
array.with(index, value)
Name Description
index Zero-based position to replace. It is converted to an integer (the fraction is cut off). A negative value counts from the end.
value The new element for that position.

Return value: a new array with the same length as the original, in which the element at index is value.

Exceptions: RangeError if index is out of range after negative indexes are resolved, that is, if it is less than -length or greater than or equal to length. Unlike bracket assignment, with() never makes an array longer.

Usage notes

  • No mutation. The array you call it on stays as it was. The returned array is always a new one.
  • Strict about the range. arr[10] = x on a short array silently creates holes, while arr.with(10, x) throws. This catches off-by-one mistakes.
  • Shallow copy. The other elements are the same references as in the original. When you replace an object that lives in the array, create a new object with spread (as in the example) instead of changing the old one.
  • Holes become undefined. The result is a dense array, so empty slots in the original turn into undefined values.
  • Missing arguments. with(1) replaces the element with undefined.
  • Generic. It works on array-likes through Array.prototype.with.call(...) and returns an array. Typed arrays have their own with() method.
  • Not a lookup. To read an element at a negative index, use at().
  • Cost. Copying makes the call proportional to the array's length. Replacing many elements one by one with with() therefore copies many times; for bulk changes, copy once with slice() or spread and assign.

Browser support

with() belongs to the newer "change array by copy" methods and works in current browsers. Because it is recent, check a compatibility table when you need older browsers or older Node.js versions.