Array.prototype.with(): replace an element in a copy (ES2023)
What you’ll learn
Section titled “What you’ll learn”- 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-1trap, and other common mistakes.
Summary
Section titled “Summary”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).
The problem it solves
Section titled “The problem it solves”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' ]How it works
Section titled “How it works”Per the specification, with(index, value):
- Reads the receiver’s
length. - Converts
indexto an integer (strings such as'2'work, fractions are truncated toward zero,NaNbecomes0) and addslengthif it is negative, the same rule asat(). - Throws a
RangeErrorif the result is below0or at or beyondlength. It never grows the array. - Creates a new plain
Arrayof the same length, copies every element, and putsvalueat 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 endconsole.log(steps.with('2', 'card')); // index is converted to an integerconsole.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 : 4RangeError: 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.
Realistic example
Section titled “Realistic example”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 3true falsetrue 52 72The 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.
Common mistakes
Section titled “Common mistakes”-
Passing
-1fromfindIndex()orindexOf().-1is a valid index forwith(): 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 foundconsole.log(items.with(i, 'HAT-S')); // [ 'MUG-01', 'TEE-M', 'HAT-S' ]Always check for
-1first. -
Trying to append.
arr.with(arr.length, x)throws aRangeError. Use[...arr, x]orarr.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 usemap. -
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.
When to use it and when not to
Section titled “When to use it and when not to”| 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() |
Compatibility
Section titled “Compatibility”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.
Interview questions
Section titled “Interview questions”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.
Key takeaways
Section titled “Key takeaways”with(index, value)(ES2023) is a non-mutatingarr[index] = value.- Negative indexes count from the end; out-of-range indexes throw
RangeError. - Guard against
-1fromfindIndex()andindexOf(). - Each call copies the whole array; batch changes to large arrays.
Related pages
Section titled “Related pages”- Array.prototype.toSorted: the non-mutating
sort(). - Array.prototype.toReversed: the non-mutating
reverse(). - Array.prototype.at: read with negative indexes.
- Rest/Spread Properties: copy and update objects.
- Spread and rest operators: array spread for appending and inserting.
- Arrays (basics)