Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Update JavaScript Arrays Immutably with `with()`

1 min read .
Update JavaScript Arrays Immutably with `with()`

Array.prototype.with() returns a copy of an array with one element replaced. The source array is left unchanged.

const colors = ['red', 'blue', 'green', 'yellow'];
const updated = colors.with(1, 'purple');

console.log(updated); // ['red', 'purple', 'green', 'yellow']
console.log(colors);  // ['red', 'blue', 'green', 'yellow']

Negative Indexes

Like at(), with() accepts negative indexes:

const values = [10, 20, 30];
console.log(values.with(-1, 99)); // [10, 20, 99]

An out-of-range index throws a RangeError, unlike ordinary assignment which can extend an array.

Compose with Other Non-Mutating Methods

const numbers = [1, 2, 3, 4, 5];
const result = numbers
  .with(3, 100)
  .map((number) => number * 2);

console.log(result);  // [2, 4, 6, 200, 10]
console.log(numbers); // unchanged

Why Use It?

with() is useful in reducers, UI state, and other code where updates should create a new array reference rather than mutate shared state.

For older runtimes, a common equivalent is:

const updated = [...colors];
updated[1] = 'purple';

Conclusion

Use with() for a concise single-element replacement that preserves the original array. It pairs naturally with JavaScript’s other copy-by-change array methods such as toSorted(), toReversed(), and toSpliced().

Related Posts

chevron-up