JavaScript Array with() Method
Last Updated :
15 Mar, 2024
The with() method in JavaScript Array returns a new array with the element at the given index replaced with the given value.
Syntax:
input_array.with(index, value)
Parameters:
- Index: RangeError is thrown if the provided index does not exist in the array.
- value: It is the value that is assigned to the specified index position.
Example 1: Consider a JavaScript array with 5 elements and replace the value present at Index position – 4 with 100.
JavaScript
let actual_array = [60, 78, 90, 34, 67];
console.log("Existing Array: ", actual_array);
// with()
let final_array = actual_array.with(4, 100);
console.log("Final Array: ", final_array);
Output:
Existing Array: [60, 78, 90, 34, 67]
Final Array: [60, 78, 90, 34, 100]
Example 2: Let’s apply map() function to this function and replace the element present at index – 4 with 100 multiplied by 2.
JavaScript
let actual_array = [60, 78, 90, 34, 67];
console.log("Existing Array: ", actual_array);
// with()
let final_array = actual_array
.with(4, 100)
.map((x) => x * 2);
console.log("Final Array: ", final_array);
Output:
Existing Array: [60, 78, 90, 34, 67]
Final Array: [60, 78, 90, 34, 200]
Share your thoughts in the comments
Please Login to comment...