JS: Array.prototype.with

By Xah Lee. Date: . Last updated: .

(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] = newval but does not change the original.

For Sparse Array, empty slots get value of undefined

🟢 TIP: good for functional programing style.

const xx = [1, 2, 3, 4];
const yy = xx.with(0,"a");

console.log(xx);
// [ 1, 2, 3, 4 ]

console.log(yy);
// [ "a", 2, 3, 4 ]

Example. No arg

// what happens if no arg
console.log([1, 2, 3, 4].with());
// [ undefined, 2, 3, 4 ]

Example. On sparse array

// on sparse array

const xx = Array(4);

const yy = xx.with(0, "a");

console.log(xx);
// [ <4 empty items> ]

console.log(yy);
// [ "a", undefined, undefined, undefined ]

Js, Array Get Set an Element by Index