Array.prototype.with()

The with() method of an Array instance is the copying version of using the bracket notation to change the value of a given index. It returns a new array with the element at the given index replaced with the given value.

Syntax

array.with(index, value)

Parameters

index

Zero-based index at which to change the array, converted to an integer.

  • Negative index counts back from the end of the array — if start < 0, start + array.length is used.
  • If start is omitted, 0 is used.
  • If the index, with negative values counted backwards, is out of bounds, a RangeError is thrown.
value

Any value to be assigned to the given index.

Return value

A new array with the element at index replaced with value.

Exceptions

RangeError

Thrown if index > array.length or index < -array.length.

Description

The with() method changes the value of a given index in the array, returning a new array with the element at the given index replaced with the given value. The original array is not modified. This allows you to chain array methods while doing manipulations.

The with() method never produces a sparse array. If the source array is sparse, the empty slots will be replaced with undefined in the new array.

The with() method is generic. It only expects the this value to have a length property and integer-keyed properties.

Examples

Creating a new array with a single element changed

const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]

Chaining array methods

With the with() method, you can update a single element in an array and then apply other array methods.

const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6).map((x) => x ** 2)); // [1, 4, 36, 16, 25]

Using with() on sparse arrays

The with() method always creates a dense array.

const arr = [1, , 3, 4, , 6];
console.log(arr.with(0, 2)); // [2, undefined, 3, 4, undefined, 6]

Calling with() on non-array objects

The with() method reads the length property of this. It then reads each integer-keyed property of this and writes it to the new array, while value is written to the given index.

const arrayLike = {
  length: 3,
  unrelated: "foo",
  0: 5,
  2: 4,
};
console.log(Array.prototype.with.call(arrayLike, 0, 1));
// [ 1, undefined, 4 ]

Specifications

Specification
ECMAScript Language Specification
# sec-array.prototype.with

Browser compatibility

BCD tables only load in the browser

See also