DEV Community

Jack Huynh
Jack Huynh

Posted on

Javascript (ES14): with()

ECMAScript proposal "Change Array by copy" by Robin Ricard and Ashley Claymore has been merge into ECMAScript standard. This proposal brings a lot of new toys, one of which is new array method: with().

The with() method is a new way to modify an array's item:

with(index, value): Array  
Enter fullscreen mode Exit fullscreen mode

The only difference is that it does not change the original array and returns a changed copy of the original array.

const arr = [1, 2, 3];

arr[1] = 4;

console.log(arr)
// [1, 4, 3] The original array is mutated
Enter fullscreen mode Exit fullscreen mode

with()

const arr = [1, 2, 3];

console.log(arr.with(1, 4)) 
// [1, 4, 3] Returns a new copy of arr with updated value.

console.log(arr) 
// [1, 2, 3] The original array is not affected
Enter fullscreen mode Exit fullscreen mode

For more information, check out the following resources:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/with

Top comments (0)