JS: Array.prototype.with
(new in ECMAScript 2023)
xArray.with(n, newval)-
- return a new copy of array, with element at index n changed to newval
- n can be negative, meaning counting from right.
this is similar to
xArray[n] = newvalbut does not change the original.For Sparse Array, empty items get value of
undefined🟢 TIP: this is good for functional programing style.
console.log([1, 2, 3].with(0, "a")); // [ "a", 2, 3 ] console.log([1, 2, 3].with(-1, "a")); // [ 1, 2, "a" ]
Edge cases
On sparse array
/* on sparse array. all empty index gets undefined */ console.log(Array(4)); // [ <4 empty items> ] console.log(Array(4).with(0, "a")); // [ "a", undefined, undefined, undefined ]
Example. No arg
// what happens if no arg console.log([1, 2, 3, 4].with()); // [ undefined, 2, 3, 4 ]