CKTIS / JavaScript
Array.prototype.with: a copy with one index replaced
with returns a shallow dense copy with one value replaced at a specified positive or negative index.
Version: ECMAScript 2023; example target: Node.js 24.22.2
Syntax
array.with(index, value)array.with(index, value) creates a new ordinary Array of the same length, writes value at the selected position, and copies every other value. It does not mutate array, does not consult Symbol.species, and unchanged objects retain the same references.
index is converted to an integer; a negative value counts from the end, so -1 selects the last position. An index below minus the length or at least the length throws RangeError. Holes are read as undefined and materialized, making the result dense.
The method is generic for array-like values and was standardized in ECMAScript 2023. A null or undefined receiver throws TypeError; length or index conversion, getter, and proxy trap failures propagate, and a length too large for an ordinary Array can also produce RangeError.
Examples
const source = [{ id: "a" }, { id: "b" }, { id: "c" }];
const changed = source.with(-2, { id: "B" });
console.log(changed.map(item => item.id).join(","));
console.log(source.map(item => item.id).join(","));
console.log(changed !== source, changed[0] === source[0]);
const dense = [, 2].with(1, 9);
console.log(dense.length, 0 in dense, dense[0] === undefined, dense[1]);
try { [1].with(2, 0); } catch (error) { console.log(error instanceof RangeError); }Result
a,B,c a,b,c true true 2 true true 9 true