The Array.with()
method is a modern JavaScript feature introduced in ECMAScript 2023 (ES14). It creates a shallow copy of an array and replaces the element at a specified index with a new value, leaving the original array unchanged. This makes it a non-mutating alternative for modifying elements in an array.
Syntax
let newArray = arr.with(index, value);
Parameters
Parameter | Description |
---|---|
index | (Required) The index of the element to replace. Can be positive or negative. |
value | (Required) The new value to set at the specified index. |
Return Value
The method returns a new array with the specified index replaced by the provided value. If the index
is out of range, the method throws a RangeError
.
Example 1: Replacing an Element
let arr = [10, 20, 30, 40, 50]; let newArr = arr.with(1, 15); console.log(newArr); // Output: [ 10, 15, 30, 40, 50 ]
Example 2: Using Negative Indices
let arr = [10, 20, 30, 40, 50]; let newArr = arr.with(-1, 99); console.log(newArr); // Output: [ 10, 20, 30, 40, 99 ]
Example 3: Modifying Nested Arrays
let arr = [[1, 2], [3, 4], [5, 6]]; let newArr = arr.with(1, [7, 8]); console.log(newArr); // Output: [[1, 2], [7, 8], [5, 6]]
Supported Browsers
Browser | Support |
---|---|
Chrome | 110+ |
Firefox | 109+ |
Safari | 16.4+ |
Edge | 110+ |
Opera | 96+ |
Internet Explorer | Not Supported |