The with() method of the Array class in JavaScript returns a new array with the element at the given index replaced with the given value, without modifying the original array.
The syntax of Array.with() method is:
arrayInstance.with(index, value)
This with() method of Array returns a new array with the element at the given index replaced with the given value, without modifying the original array.
Parameter | Optional/Required | Description |
---|---|---|
index | required | The index of the element to replace. |
value | required | The value to replace at the specified index. |
Array.with() returns value of type Array
.
In JavaScript, we can use the with() method to replace an element at a specific index in an array.
For example,
const arr = [1, 2, 3, 4, 5];
const newArr = arr.with(2, 10);
console.log(newArr);
[1, 2, 10, 4, 5]
In JavaScript, we can use the with() method to replace an element at a specific index in an array.
For example,
const arr = ['apple', 'banana', 'cherry', 'date'];
const newArr = arr.with(1, 'orange');
console.log(newArr);
['apple', 'orange', 'cherry', 'date']
In this JavaScript tutorial, we learned about with() method of Array: the syntax and few working examples with output and detailed explanation for each example.