The JavaScript Array.prototype.with() method is a relatively new addition to the array methods that allows you to create a new array with a modified value at a specified index. This method does not mutate the original array but returns a new array with the desired changes. This is particularly useful for maintaining immutability in functional programming practices.
Syntax
array.with(index, value);
Parameters
Parameters | Description |
---|---|
index | The position in the array where the value should be replaced. |
value | The new value to be set at the specified index. |
Return Value
Value | Description |
---|---|
Array Object | Returns a new array with the value replaced at the specified index. The original array remains unchanged. |
Example 1: Basic Usage
This example demonstrates how to use the with() method to replace an element at a specific index in an array.
let arr = [1, 2, 3]; let newArr = arr.with(1, 10); console.log(newArr); // [1, 10, 3] console.log(arr); // [1, 2, 3]
Example 2: Replacing an Element in a Large Array
This example shows how to replace an element in a larger array using the with() method.
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let newArr = arr.with(5, 50); console.log(newArr); // [0, 1, 2, 3, 4, 50, 6, 7, 8, 9] console.log(arr); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 3: Handling Negative Indices
The with() method also supports negative indices, which count back from the end of the array.
let arr = ['a', 'b', 'c', 'd']; let newArr = arr.with(-1, 'z'); console.log(newArr); // ['a', 'b', 'c', 'z'] console.log(arr); // ['a', 'b', 'c', 'd']
Example 4: Using with() in a Function
This example demonstrates how to use the with() method within a function to update an array without mutating the original array.
function updateArray(arr, index, value) { return arr.with(index, value); } let arr = [100, 200, 300]; let newArr = updateArray(arr, 1, 250); console.log(newArr); // [100, 250, 300] console.log(arr); // [100, 200, 300]
Example 5: Out of Bounds Index
If the specified index is out of the bounds of the array, the with() method throws an error.
let arr = [1, 2, 3]; try { let newArr = arr.with(5, 100); } catch (error) { console.log(error.message); // "Index out of range" }
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
110 | 110 | 115 | 96 | 16 |