Skip to content

Array.prototype.with(): replace an element in a copy (ES2023)

  • How with(index, value) replaces one element without mutating the array.
  • How it treats negative, fractional and out-of-range indexes.
  • How to use it for immutable state updates, such as a cart reducer.
  • The findIndex() returning -1 trap, and other common mistakes.

TL;DR: array.with(index, value) returns a new array that is a copy of array with the element at index replaced by value. Negative indexes count from the end. An index outside the array throws a RangeError. It is the non-mutating form of array[index] = value.

It was added in ECMAScript 2023 by the “Change Array by Copy” proposal, alongside toSorted(), toReversed() and toSpliced(). It is supported in all current browsers and Node.js 20+ (see Compatibility).

Updating one element of an array that other code also holds, such as UI state, needs a copy. Before ES2023 that took two statements (copy, then assign), a map over every index, or a spread of two slices. All of them work, but none says “replace element i” directly.

Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs). All outputs shown were produced with Node.js 22.23. The examples use an invented order-management app, OrdersPortal.

const statuses = ['paid', 'pending', 'paid'];
// Before: copy, then assign (two statements), or map over every index.
const copy = statuses.slice();
copy[1] = 'paid';
const mapped = statuses.map((s, i) => (i === 1 ? 'paid' : s));
// After: one expression that returns a new array.
const updated = statuses.with(1, 'paid');
console.log(statuses, copy, mapped, updated);

Output:

[ 'paid', 'pending', 'paid' ] [ 'paid', 'paid', 'paid' ] [ 'paid', 'paid', 'paid' ] [ 'paid', 'paid', 'paid' ]

Per the specification, with(index, value):

  1. Reads the receiver’s length.
  2. Converts index to an integer (strings such as '2' work, fractions are truncated toward zero, NaN becomes 0) and adds length if it is negative, the same rule as at().
  3. Throws a RangeError if the result is below 0 or at or beyond length. It never grows the array.
  4. Creates a new plain Array of the same length, copies every element, and puts value at the target index.

As with the other copying methods, holes become undefined, it works generically on array-likes, the result is never a subclass instance, and the copy is shallow. Typed arrays have their own with(), which converts value to the element type.

const steps = ['cart', 'address', 'payment', 'review'];
console.log(steps.with(0, 'basket'));
console.log(steps.with(-1, 'confirm')); // negative index counts from the end
console.log(steps.with('2', 'card')); // index is converted to an integer
console.log(steps.with(1.9, 'shipping')); // truncated to 1
// Out of range throws instead of growing the array.
for (const i of [4, -5]) {
try { steps.with(i, 'x'); } catch (e) { console.log(e.constructor.name + ':', e.message); }
}
// Holes become undefined; array-likes work; result is a plain Array.
console.log([1, , 3].with(0, 0));
console.log(Array.prototype.with.call({ length: 2, 0: 'a', 1: 'b' }, 1, 'B'));
// Typed arrays: the value is converted to the element type.
console.log(new Uint8Array([1, 2, 3]).with(0, 300));
// Chaining: each call returns a new array.
console.log(steps.with(0, 'basket').with(-1, 'confirm'));

Output (the RangeError message is V8’s wording):

[ 'basket', 'address', 'payment', 'review' ]
[ 'cart', 'address', 'payment', 'confirm' ]
[ 'cart', 'address', 'card', 'review' ]
[ 'cart', 'shipping', 'payment', 'review' ]
RangeError: Invalid index : 4
RangeError: Invalid index : -5
[ 0, undefined, 3 ]
[ 'a', 'B' ]
Uint8Array(3) [ 44, 2, 3 ]
[ 'basket', 'address', 'payment', 'confirm' ]

300 stored in a Uint8Array wraps to 44 (300 modulo 256), exactly as a normal assignment would.

The OrdersPortal cart is held in immutable state, updated by a reducer. Changing a quantity must produce a new items array in which only the changed line item is a new object, so components that render other lines can skip re-rendering.

const initial = {
items: [
{ sku: 'MUG-01', qty: 1, price: 12 },
{ sku: 'TEE-M', qty: 2, price: 20 },
],
};
function cartReducer(state, action) {
switch (action.type) {
case 'setQty': {
const i = state.items.findIndex((it) => it.sku === action.sku);
if (i === -1) return state; // never call with(-1, ...): it would replace the LAST item
const item = state.items[i];
return { ...state, items: state.items.with(i, { ...item, qty: action.qty }) };
}
case 'add':
return { ...state, items: [...state.items, { ...action.item }] };
default:
return state;
}
}
const s1 = cartReducer(initial, { type: 'setQty', sku: 'TEE-M', qty: 3 });
const s2 = cartReducer(s1, { type: 'setQty', sku: 'NOPE', qty: 9 });
const total = (s) => s.items.reduce((sum, it) => sum + it.qty * it.price, 0);
console.log(initial.items[1].qty, s1.items[1].qty);
console.log(s1.items[0] === initial.items[0], s1.items[1] === initial.items[1]);
console.log(s2 === s1, total(initial), total(s1));

Output:

2 3
true false
true 52 72

The unchanged mug line keeps its identity (true), the T-shirt line is a new object (false), and an unknown SKU returns the same state object, so nothing re-renders. The object spread used to copy the line item is covered in Rest/Spread Properties. Adding an item uses array spread, because with() can only replace, never append.

  • Passing -1 from findIndex() or indexOf(). -1 is a valid index for with(): it means the last element. A “not found” result silently overwrites the last item instead of throwing.

    const items = ['MUG-01', 'TEE-M', 'CAP-L'];
    const i = items.indexOf('HAT-S'); // -1: not found
    console.log(items.with(i, 'HAT-S')); // [ 'MUG-01', 'TEE-M', 'HAT-S' ]

    Always check for -1 first.

  • Trying to append. arr.with(arr.length, x) throws a RangeError. Use [...arr, x] or arr.toSpliced(arr.length, 0, x).

  • Expecting a deep update. with() replaces the slot, not properties of the object in it. Build the new element yourself, as the reducer does with { ...item, qty }.

  • Chaining many with() calls. Each call copies the whole array. To change many indexes, copy once and assign in a loop, or use map.

  • Using it in a hot loop over a big array. with() is O(n) per call; a loop of n updates becomes O(n²). Mutate a private copy instead.

Need Use
Replace one element; the array is shared or is state with(i, value)
Replace one element in an array you own arr[i] = value (no copy)
Replace several elements one map, or one copy plus assignments
Insert or remove elements in a copy toSpliced(), or spread with slice
Sorted or reversed copy toSorted(), toReversed()
Read an element by negative index at()

According to MDN’s browser compatibility data, Array.prototype.with and TypedArray.prototype.with are supported in Chrome 110, Edge 110, Firefox 115, Safari 16 (including iOS), Node.js 20.0.0, Deno 1.31 and Bun 1.0. Internet Explorer never supported them.

TypeScript: the typings are in lib.es2023.array.d.ts. With an older lib or target, TypeScript 6.0 reports Property 'with' does not exist on type ... and suggests es2023 or later. TypeScript does not polyfill it; use core-js for Node.js 18 or older browsers.

1. What does ['a', 'b', 'c'].with(-1, 'z') return, and what does ['a', 'b', 'c'].with(3, 'z') do? The first returns ['a', 'b', 'z']: negative indexes count from the end. The second throws a RangeError, because with() only replaces existing positions and never extends the array, unlike arr[3] = 'z'.

2. Why is items.with(items.findIndex(fn), newItem) dangerous? If nothing matches, findIndex returns -1, which with() treats as the last index, so the last element is silently replaced. Check for -1 and handle “not found” explicitly.

3. Senior scenario: a spreadsheet-like grid of 50,000 cells is stored as an immutable array, and each keystroke calls cells.with(i, value). Bulk paste of 5,000 cells is slow. What do you do? Each with() copies all 50,000 elements, so a paste makes 5,000 full copies. Batch the change: copy once (cells.slice()), apply all assignments to the private copy, and publish it as the new state. For frequent fine-grained updates on large data, consider a structure that shares unchanged parts, such as chunked rows (copy only the changed chunk) or a persistent data structure library.

  • with(index, value) (ES2023) is a non-mutating arr[index] = value.
  • Negative indexes count from the end; out-of-range indexes throw RangeError.
  • Guard against -1 from findIndex() and indexOf().
  • Each call copies the whole array; batch changes to large arrays.