Array.prototype.with()
with(index, value) Returns:
array · Added in vES2023 · Updated March 15, 2026 · Array Methods array with immutable es2023
The with() method returns a new array with the element at the specified index replaced with the new value. Unlike the traditional approach of mutating an array using bracket notation, with() creates a new array and leaves the original unchanged—making your code more predictable and functional.
This method is part of the ES2023 array copying methods that provide immutable alternatives to mutating operations.
Syntax
array.with(index, value)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
index | integer | Required | The zero-based index at which to replace the element. Negative indices count from the end of the array. |
value | any | Required | The value to place at the specified index. |
Examples
Basic usage
const fruits = ['apple', 'banana', 'cherry'];
// Replace element at index 1
const updated = fruits.with(1, 'blueberry');
console.log(updated);
// ['apple', 'blueberry', 'cherry']
// Original array remains unchanged
console.log(fruits);
// ['apple', 'banana', 'cherry']
Using negative indices
const nums = [1, 2, 3, 4, 5];
// Replace last element using negative index
const result = nums.with(-1, 10);
console.log(result);
// [1, 2, 3, 4, 10]
// Replace second-to-last element
console.log(nums.with(-2, 99));
// [1, 2, 3, 99, 5]
Updating nested array elements
const matrix = [
[1, 2],
[3, 4]
];
// Replace entire row at index 0
const newMatrix = matrix.with(0, [10, 20]);
console.log(newMatrix);
// [[10, 20], [3, 4]]
console.log(matrix);
// [[1, 2], [3, 4]] - unchanged
Common Patterns
Immutable array updates in Redux-style state
function updateItem(arr, index, newValue) {
return arr.with(index, newValue);
}
const state = [1, 2, 3, 4, 5];
const newState = updateItem(state, 2, 42);
// [1, 2, 42, 4, 5]
Chain with other array methods
const data = ['a', 'b', 'c', 'd'];
// Chain with filter, map, etc.
const result = data
.filter((_, i) => i !== 1)
.with(0, 'z');
console.log(result);
// ['z', 'c', 'd']
When to Use
- Functional programming: When you need to avoid mutating state
- React/Redux: For immutable state updates
- Debugging: When you want to preserve the original array for comparison
When Not to Use
- Performance-critical code: Creating new arrays has overhead; use mutating methods (
arr[i] = value) when performance matters - Simple scripts: When you don’t care about immutability
See Also
Array.prototype.toSorted()— Return a sorted copy of an arrayArray.prototype.toSpliced()— Return a copy with elements removed/inserted