Array.prototype.with Replaces One Index Safely

Replace a single element immutably with Array.prototype.with, supporting negative indices from the end while throwing RangeError on out-of-bounds updates.

JavascriptData Integrity

Code

snippet
const stages = ['lint', 'test', 'package', 'deploy'];

// Replace at a positive index without mutating `stages`
const patched = stages.with(2, 'bundle');
console.log('patched:', JSON.stringify(patched));
console.log('source :', JSON.stringify(stages));

// Negative indices count backward from the tail
const renamedTail = patched.with(-1, 'publish');
console.log('tail   :', JSON.stringify(renamedTail));

// Unlike `stages[10] = 'x'` (which creates sparse holes), .with() throws RangeError
try {
  stages.with(10, 'overflow');
} catch (err) {
  console.log('out-of-bounds:', err.name, err.message.includes('Invalid index'));
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

patched: ["lint","test","bundle","deploy"]
source : ["lint","test","package","deploy"]
tail   : ["lint","test","bundle","publish"]
out-of-bounds: RangeError true

Execution breakdown — Array.prototype.with Replaces One Index Safely

Demo state sits in top-level bindings: stages, patched, renamedTail.

Points of care

  • The import surface (if any) is all standard library, all versioned with the language itself.

Using it

The run prints patched:, source :, tail : — each prefix names the step that produced it.

Key statements

const stages = ['lint', 'test', 'package', 'deploy'];
const renamedTail = patched.with(-1, 'publish');
const patched = stages.with(2, 'bundle');

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. Its state lives in module-level bindings: `stages`, `patched`, `renamedTail`.