Sub topic 6
Replacing one element with with
This chapter assumes you know how to index into a JavaScript array, how bracket assignment (arr[i] = value) works, and that objects are passed by reference. It covers Array.prototype.with, the copying counterpart of bracket assignment. Negative indices and out-of-range errors get their own chapter later, so this one covers them only as far as you need them to use with correctly.
What with does
with(index, value) returns a new array that matches the original except at one position, which holds value. The original array is not touched. The new array always has the same length as the original.
const original = ["a", "b", "c"];
const copy = original.with(1, "B");
console.log(copy); // ["a", "B", "c"]
console.log(original); // ["a", "b", "c"]
console.log(copy === original); // falseThe method name reads like a sentence: "the original, with index 1 set to "B"". It takes exactly two arguments. Unlike toSpliced, it cannot insert or remove elements. It can only replace one.
Why bracket assignment is the method it replaces
Bracket assignment is the most direct way to change an element, and it has two properties that cause bugs in shared code.
First, it changes the array in place, so every variable that refers to that array sees the change. Second, it can grow the array. Assigning past the end raises length and leaves holes, which are empty slots with no value at all.
const letters = ["a", "b", "c"];
const alias = letters;
alias[1] = "B";
console.log(letters); // ["a", "B", "c"] (changed through the alias)
letters[5] = "f";
console.log(letters.length); // 6
console.log(3 in letters); // false (index 3 is a hole)with has neither property. It never changes the receiver, and it never changes the length.
| Behavior | `arr[i] = v` | `arr.with(i, v)` |
|---|---|---|
| Changes the original array | Yes | No |
| Return value | `v` (the assigned value) | A new array |
| Index past the end | Grows the array and creates holes | Throws `RangeError` |
| Negative index such as `-1` | Creates a property named `"-1"` | Counts from the end |
| Works on a frozen array | No (fails, or throws in strict mode) | Yes |
| Usable as an expression in a chain | Not usefully | Yes |
The return value row matters more than it seems. Because arr[i] = v evaluates to v, you cannot write return arr[i] = v and get the array back. with gives you the array, so you can return it, pass it to a function, or chain another method onto it.
How with works internally
The specification describes with as a short algorithm. Knowing the steps explains every edge case in this chapter.
Several details follow from these steps:
- The range check happens before any copying. A bad index costs nothing and leaves no partial result.
- The new array is a plain
Arraycreated fresh. It does not inherit the receiver's frozen state, subclass, or extra properties. - Every position from 0 to
length - 1is read with a normal property lookup, so the result is always dense, with no holes. The sparse arrays chapter covers what that means for arrays that already have holes. - The copy is shallow. Objects in the array are copied by reference. A later chapter covers the consequences.
How the index is converted
with converts its first argument to an integer before it does anything else. That conversion is forgiving, and it can hide mistakes:
const v = [10, 20, 30];
console.log(v.with("1", 99)); // [10, 99, 30] (string converted to 1)
console.log(v.with(1.9, 99)); // [10, 99, 30] (fraction truncated toward zero)
console.log(v.with(NaN, 99)); // [99, 20, 30] (NaN becomes 0)
console.log(v.with()); // [undefined, 20, 30]The last two lines are where bugs come from. If an index comes from Number(input) or indexOf and something goes wrong, NaN silently becomes 0 and you overwrite the first element. Calling with() with no arguments does the same thing and writes undefined there. indexOf returns -1 when nothing matches, and -1 is a valid negative index, so the last element gets replaced:
const tags = ["red", "green", "blue"];
const i = tags.indexOf("purple"); // -1, not found
console.log(tags.with(i, "violet")); // ["red", "green", "violet"] (wrong)Working with frozen arrays
Object.freeze stops changes to an array, and const only stops reassignment of the variable. with reads from the receiver and never writes to it, so it works on frozen arrays. That makes it a natural fit for data you want to protect.
"use strict";
const config = Object.freeze(["dev", "info"]);
try {
config[1] = "debug";
} catch (err) {
console.log(err instanceof TypeError); // true
}
const next = config.with(1, "debug");
console.log(next); // ["dev", "debug"]
console.log(Object.isFrozen(next)); // false
console.log(config); // ["dev", "info"]The result is not frozen. If you want the new array frozen as well, wrap the call: Object.freeze(config.with(1, "debug")).
Comparing with the hand-written alternatives
Before ES2023, people wrote this operation by hand in one of two ways. Both look equivalent to with, and both behave differently at the edges.
const withSpread = (arr, i, value) => {
const copy = [...arr];
copy[i] = value;
return copy;
};
const withMap = (arr, i, value) =>
arr.map((item, j) => (j === i ? value : item));
const data = [1, 2, 3];
console.log(data.with(1, 0)); // [1, 0, 3]
console.log(withSpread(data, 1, 0)); // [1, 0, 3]
console.log(withMap(data, 1, 0)); // [1, 0, 3]
// Out of range
console.log(withSpread(data, 5, 0).length); // 6 (grew, with holes)
console.log(withMap(data, 5, 0)); // [1, 2, 3] (silently unchanged)
try {
data.with(5, 0);
} catch (err) {
console.log(err.name); // "RangeError"
}
// Negative index
console.log(withMap(data, -1, 0)); // [1, 2, 3] (no match)
console.log(data.with(-1, 0)); // [1, 2, 0]| Approach | Out-of-range index | Negative index | Holes in input |
|---|---|---|---|
| `arr.with(i, v)` | Throws `RangeError` | Counts from end | Become `undefined` |
| Spread, then assign | Grows array | Adds a `"-1"` property | Become `undefined` |
| `map` with index check | Returns unchanged copy | No match | Stay holes |
Only with reports a bad index. The other two fail silently, which usually means the bug shows up somewhere far from its cause. If you are replacing hand-written helpers with with, look for callers that relied on the silent behavior, for example code that appends with withSpread(arr, arr.length, x). After the switch, those callers throw.
Chaining and the cost of copying
Because with returns an array, you can chain several replacements:
const board = ["", "", "", "", "", "", "", "", ""];
const afterTwoMoves = board.with(4, "X").with(0, "O");
console.log(afterTwoMoves); // ["O", "", "", "", "X", "", "", "", ""]
console.log(board.every((cell) => cell === "")); // trueEach call copies the whole array, so it costs time in proportion to the array's length. One or two calls on a UI-sized list are cheap. Calling with in a loop over many indices of a large array costs O(n × m), where n is the length and m is the number of updates. In that case, copy once and mutate the private copy:
function setMany(arr, updates) {
const copy = [...arr];
for (const [index, value] of updates) {
copy[index] = value;
}
return copy;
}
const prices = [5, 10, 15, 20];
console.log(setMany(prices, [[0, 6], [3, 21]])); // [6, 10, 15, 21]
console.log(prices); // [5, 10, 15, 20]Mutation is fine here because no other code can see copy until the function returns. The caller still gets a new array and an unchanged original. This version keeps the spread approach's out-of-range behavior, so validate the indices first if they come from outside the function.
Choosing with
Use with when you need to replace exactly one element and other code may hold a reference to the original array. Typical cases are state values, function arguments, and frozen data. Use toSpliced when the length should change. Use map when you are changing elements by a condition, such as "every item whose id matches," and you don't know the index.
Exercise
Given const xs = [1, 2, 3], what does each line print or do? (a) console.log(xs.with(-3, 9)); (b) console.log(xs.with(3, 9)); (c) console.log(xs.with("2", 9)); (d) console.log(xs.with(NaN, 9));
Show answer
(a) [9, 2, 3], because -3 + 3 = 0. (b) Throws a RangeError, because 3 is not less than the length. (c) [1, 2, 9], because the string "2" is converted to the integer 2. (d) [9, 2, 3], because NaN converts to 0. In every case that does not throw, xs is still [1, 2, 3].
Exercise
A function marks an item as selected: const select = (items, id) => items.with(items.findIndex((x) => x.id === id), { id, selected: true }); What goes wrong when id is not in the list, and how would you fix it?
Show answer
findIndex returns -1, and with treats -1 as the last index, so the function silently overwrites the last item with the new object. Store the index first and check it: const i = items.findIndex((x) => x.id === id); if (i === -1) return items; return items.with(i, { id, selected: true });. Returning the original array unchanged when nothing matches also lets reference-equality checks skip unnecessary work.
Exercise
Why does Object.freeze(["a", "b"]).with(0, "z") succeed, and is the result frozen?
Show answer
It succeeds because with only reads from the receiver and writes into a brand-new array, so the freeze on the original is never violated. The result is a new plain Array and is not frozen. Wrap the call in Object.freeze if you need it frozen.