#JS with() new Array method
The with method is a new addition to JavaScript's array methods introduced in ECMAScript 2023 (ES14). It allows you to create a new array with a value replaced at a specific index, without modifying the original array.
to solve this problem of mutability and achieve immutability while changing an element of an array.
The with() method takes two parameters:
Here's the syntax and an example of how to use the with method:
let originalArray = [1, 2, 3, 4, 5];
let newArray = originalArray.with(2, 99); // replaces the value at index 2 with 99
console.log(originalArray); // [1, 2, 3, 4, 5]
console.log(newArray); // [1, 2, 99, 4, 5]
In this example:
As the with() method returns an array, you can chain the output of the with() method along with other array methods, like map(), filter(), reduce(), some(), every() etc.