Array.with()
The Array.with()
method in JavaScript creates a new array with a specified element replaced at a given index. It does not modify the original array but instead returns a new one.
Syntax
arrayInstance.with(index, value)
Parameters
Parameter | Description |
---|---|
index | The zero-based index of the element to replace. Negative indices count back from the end of the array. |
value | The value to set at the specified index in the new array. |
Return Value
The with()
method returns a new array that is identical to the original, except the specified index is replaced with the provided value.
Examples
1. Replacing an Element in an Array
This example demonstrates replacing an element at a specific index.
const fruits = ["apple", "banana", "cherry"];
const newFruits = fruits.with(1, "orange");
console.log(newFruits);
Output
["apple", "orange", "cherry"]
- The original array
fruits
remains unchanged. - The method replaces the element at index
1
(“banana”) with"orange"
in the new array.
2. Using Negative Indices
Negative indices allow you to replace elements from the end of the array.
const numbers = [10, 20, 30, 40];
const newNumbers = numbers.with(-1, 50);
console.log(newNumbers);
Output
[10, 20, 30, 50]
Here, -1
refers to the last element in the array, which is replaced with 50
.
3. Replacing an Element Beyond Bounds
If the specified index is out of range, the method throws a RangeError
.
const items = [1, 2, 3];
try {
const newItems = items.with(5, 4);
} catch (e) {
console.error(e.message);
}
Output
Invalid index : 5
Ensure the index is within the valid bounds of the array when using with()
.
4. Preserving Original Array
The original array remains unchanged after using the with()
method.
const letters = ["a", "b", "c"];
const newLetters = letters.with(0, "z");
console.log(newLetters);
console.log(letters);
Output
[ 'z', 'b', 'c' ]
[ 'a', 'b', 'c' ]
The original array letters
remains unchanged, demonstrating that with()
creates a new array.