JS: Array.prototype.with

By Xah Lee. Date: .

(new in JS: 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.

💡 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. convert sparse array to dense array

// convert sparse array to dense array

const xx = Array(4);

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

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

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

Example. on array-like object

// example of Array.prototype.with on array-like object

// create a array-like object
let xx = { 0: "a", 1: "b", length: 2 };

const yy = Reflect.apply(Array.prototype.with, xx, [0, "a"]);

console.log(xx);
// { "0": "a", "1": "b", length: 2 }

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

console.log(Array.isArray(yy));
// true

Js, Array Get Set an Element by Index