Array.prototype.with()

Create a new array with a single element changed at a specific index without mutating the original array.

Explanation

  • array.with(index, value): Returns a new array with the element at index replaced by value.
  • Immutable alternative to array[index] = value for functional programming patterns.
  • Supports negative indices to count from the end of the array.
  • Throws RangeError if index is out of bounds.

Usage

To update array elements immutably:

const fruits = ['apple', 'banana', 'orange'];

// Replace element at index 1
const updated = fruits.with(1, 'mango');
console.log(updated); // ['apple', 'mango', 'orange']
console.log(fruits);  // ['apple', 'banana', 'orange'] (unchanged)

// Use negative index
const colors = ['red', 'green', 'blue'];
const newColors = colors.with(-1, 'purple');
console.log(newColors); // ['red', 'green', 'purple']

// Useful in React state updates
setItems(items.with(index, newValue));

// Chain with other immutable methods
const result = [1, 2, 3, 4]
  .with(1, 10)
  .map(x => x * 2); // [2, 20, 6, 8]