Array.prototype.with
Returns a new array with the element at the given index replaced with the given value, without modifying the original array
Syntax
array.with(index, value)Parameters
| Parameter | Type | Description |
|---|---|---|
| index | number | Zero-based index of the element to replace. Negative values count from end |
| value | T | The value to assign to the given index |
Return Value
A new array with the element at the index replaced
Examples
const arr = [1, 2, 3, 4, 5];
const updated = arr.with(2, 99);
console.log(updated); // [1, 2, 99, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5] (unchanged)const colors = ['red', 'green', 'blue'];
console.log(colors.with(-1, 'yellow')); // ['red', 'green', 'yellow']const data = [10, 20, 30];
const chain = data.with(0, 11).with(2, 33);
console.log(chain); // [11, 20, 33]Understanding Array.prototype.with
The Array.prototype.with method in JavaScript returns a new array with the element at the given index replaced with the given value, without modifying the original array. It belongs to the Array object and is one of the most widely used methods for working with array values in modern JavaScript and TypeScript applications.
The method signature is array.with(index, value). It accepts 2 parameters: index, value. When called, it returns a new array with the element at the index replaced. Understanding when and how to use with() helps you write more expressive, readable code.
Common use cases for Array.prototype.with include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like array-tosorted, array-toreversed, array-tospliced, enabling you to chain operations together for complex data manipulation pipelines.
Supported in Chrome 110+, Firefox 115+, Safari 16+, Edge 110+, and Node.js 20+.
Browser Compatibility
Supported in Chrome 110+, Firefox 115+, Safari 16+, Edge 110+, and Node.js 20+.
Related Methods
Array.prototype.toSortedReturns a new array with the elements sorted in ascending order, without modifying the original array
Array.prototype.toReversedReturns a new array with the elements in reversed order, without modifying the original array
Array.prototype.toSplicedReturns a new array with some elements removed and/or replaced at a given index, without modifying the original array
More Array Methods
Other methods in the Array object
Related Tools
More Array Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.