Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.with

Returns a copy of an array with one element replaced.

Available since: ES2023

Syntax

array.with(index, value)

Parameters

ParameterTypeDescription
indexnumberThe index of the element to replace. A negative one counts from the end.
valueanyThe new value.

Return value

ArrayA new array with the element replaced.

Examples

Replacing an element in a copy:

const sizes = ['S', 'M', 'L'];
 
console.log(sizes.with(1, 'XL').join(', '));
console.log(sizes.join(', '));

Output:

S, XL, L
S, M, L

Replacing the last element:

console.log([1, 2, 3].with(-1, 30).join(', '));

Output:

1, 2, 30

Notes

The immutable version of array[index] = value. An index outside the array throws a RangeError.

See also

In the tutorial

  • Array methods — How to add and remove array elements in JavaScript: push, pop, shift, unshift, slice, splice, concat and join.

Thanks for reading!

Donate to the site — we work hard for you.