Sub topic 7
Negative indices and out-of-range errors
This chapter assumes you already know how with(index, value) returns a copy with one element replaced, as covered in the previous chapter. You should also be comfortable with zero-based indexing, bracket assignment (arr[i] = x), and try...catch. The chapter covers two rules that set with apart from bracket assignment. First, with reads negative indices as counting from the end. Second, it throws a RangeError when the index falls outside the array, where bracket assignment would grow the array.
How `with` resolves an index
When you call arr.with(index, value), the engine resolves index to an actual position before it copies anything. The steps follow the ECMAScript specification:
- Convert
indexto an integer. Fractions are truncated toward zero,NaNbecomes0, andInfinitystays infinite. - If the result is zero or positive, use it as is.
- If it is negative, add the array's length to it, so
-1becomeslength - 1. - If the final position is below
0or at or abovelength, throw aRangeError. - Otherwise, copy the array and put
valueat that position.
The check runs before any copy is made. When with throws, no new array exists, and the original was never touched.
Counting from the end
Negative indices let you target elements near the end without writing arr.length - 1:
const steps = ["draft", "review", "approve", "publish"];
console.log(steps.with(-1, "ship")); // ["draft", "review", "approve", "ship"]
console.log(steps.with(-2, "sign")); // ["draft", "review", "sign", "publish"]
console.log(steps.with(-4, "start")); // ["start", "review", "approve", "publish"]
console.log(steps); // ["draft", "review", "approve", "publish"]For an array of length n, the valid indices are -n through n - 1. Each element has two names: index 0 is also -n, and index n - 1 is also -1.
| Array length | Valid non-negative indices | Valid negative indices | Example that throws |
|---|---|---|---|
| 4 | 0, 1, 2, 3 | -1, -2, -3, -4 | `with(4, x)`, `with(-5, x)` |
| 1 | 0 | -1 | `with(1, x)`, `with(-2, x)` |
| 0 | none | none | `with(0, x)`, `with(-1, x)` |
Every call to with on an empty array throws, because no index exists to replace.
with follows the same counting rule as Array.prototype.at. The two differ on out-of-range indices: at returns undefined, and with throws.
const letters = ["a", "b", "c"];
console.log(letters.at(-1)); // "c"
console.log(letters.at(5)); // undefined
try {
letters.with(5, "z");
} catch (err) {
console.log(err instanceof RangeError); // true
}Why `with` throws instead of growing the array
Bracket assignment accepts any index. A large index extends the array and leaves holes behind. A negative index does not count from the end. It creates an ordinary property named "-1" that array methods ignore.
const a = [1, 2, 3];
a[5] = 6;
console.log(a.length); // 6
console.log(a); // [1, 2, 3, <2 empty items>, 6]
const b = [1, 2, 3];
b[-1] = 0;
console.log(b.length); // 3
console.log(b); // [1, 2, 3, "-1": 0]
console.log(b.at(-1)); // 3Both results are almost always bugs, and neither raises an error. with was designed to replace an existing element and nothing else. When the index is wrong, it fails loudly at the point of the mistake, so the problem doesn't show up later as a bad array length or a missing value.
| Operation | `arr[10] = x` on length 3 | `arr[-1] = x` | Mutates original |
|---|---|---|---|
| Bracket assignment | Grows to length 11 with holes | Adds a `"-1"` property | Yes |
| `arr.with(i, x)` | Throws `RangeError` | Replaces the last element | No |
If you need to append, use [...arr, x] or arr.toSpliced(arr.length, 0, x). with is the wrong tool for that job.
Index conversion edge cases
The integer conversion in step 1 accepts more than integers, and it produces a few surprising results:
const nums = [10, 20, 30];
console.log(nums.with(1.9, 0)); // [10, 0, 30] (1.9 truncates to 1)
console.log(nums.with(-0.5, 0)); // [0, 20, 30] (-0.5 truncates to 0)
console.log(nums.with("2", 0)); // [10, 20, 0] (string converted to 2)
console.log(nums.with(NaN, 0)); // [0, 20, 30] (NaN becomes 0)
console.log(nums.with(undefined, 0)); // [0, 20, 30] (undefined becomes NaN, then 0)
for (const bad of [3, -4, Infinity, -Infinity]) {
try {
nums.with(bad, 0);
} catch (err) {
console.log(bad, err.constructor.name); // each logs RangeError
}
}The NaN and undefined cases cause the most trouble. A value computed as NaN, or a forgotten argument, quietly replaces the first element. To catch these cases, check the index yourself with Number.isInteger before calling with.
const todos = [
{ id: 1, text: "Write" },
{ id: 2, text: "Review" }
];
// Bug: id 99 does not exist, so findIndex returns -1
const wrong = todos.with(
todos.findIndex((t) => t.id === 99),
{ id: 99, text: "Oops" }
);
console.log(wrong[1].text); // "Oops", the "Review" item was overwritten
// Fix: guard the not-found case
function updateById(list, id, update) {
const i = list.findIndex((t) => t.id === id);
if (i === -1) return list;
return list.with(i, { ...list[i], ...update });
}
console.log(updateById(todos, 99, { text: "Oops" }) === todos); // true
console.log(updateById(todos, 2, { text: "Edit" })[1].text); // "Edit"When nothing is found, the guarded version returns the original array. That suits state-driven code, because an unchanged reference tells React or Redux that nothing changed.
`toSpliced` clamps instead of throwing
toSpliced also accepts negative positions, but it handles out-of-range values differently. It clamps them into range and never throws a RangeError for them. A negative start counts from the end, and a start below -length becomes 0. A start greater than length becomes length, and deleteCount is limited to the elements that remain.
const months = ["Jan", "Feb", "Mar", "Apr"];
console.log(months.toSpliced(-1, 1)); // ["Jan", "Feb", "Mar"]
console.log(months.toSpliced(-100, 1)); // ["Feb", "Mar", "Apr"] (start clamped to 0)
console.log(months.toSpliced(100, 0, "May")); // ["Jan", "Feb", "Mar", "Apr", "May"]
console.log(months.toSpliced(2, 100)); // ["Jan", "Feb"]| Method | Negative index | Index past the end |
|---|---|---|
| `with` | Counts from the end | Throws `RangeError` |
| `toSpliced` | Counts from the end | Clamped to `length` |
| `at` | Counts from the end | Returns `undefined` |
| `arr[i] = x` | Creates a `"-1"` property | Grows the array |
Clamping makes toSpliced forgiving. It also lets the findIndex bug through: toSpliced(-1, 1) removes the last element when you meant to remove nothing. The same -1 guard applies to toSpliced.
Handling the error deliberately
In most code, a RangeError from with means there is a logic bug, and letting it propagate is the right call. When an index comes from outside your code, such as user input, a URL parameter, or a message, validate it first. That keeps error handling in your hands:
function safeWith(arr, index, value) {
if (!Number.isInteger(index) || index < -arr.length || index >= arr.length) {
return arr;
}
return arr.with(index, value);
}
const row = ["a", "b", "c"];
console.log(safeWith(row, -1, "z")); // ["a", "b", "z"]
console.log(safeWith(row, 7, "z")); // ["a", "b", "c"]
console.log(safeWith(row, NaN, "z")); // ["a", "b", "c"]Number.isInteger rejects NaN, fractions, strings, and Infinity, which closes the silent conversion gaps described earlier. Returning the original array marks a no-op. If the caller needs to know that the update was skipped, throw your own error or return a flag.
Exercise
Given const xs = ["p", "q", "r"];, what does each call produce: xs.with(-3, "z"), xs.with(-4, "z"), xs.with(2.99, "z"), and xs.toSpliced(-4, 1)?
Show answer
xs.with(-3, "z") returns ["z", "q", "r"], because -3 + 3 = 0. xs.with(-4, "z") throws a RangeError, because -4 + 3 = -1 is below 0. xs.with(2.99, "z") returns ["p", "q", "z"], because 2.99 truncates to 2. xs.toSpliced(-4, 1) returns ["q", "r"], because the start is clamped to 0 and one element is removed. In every case, xs is unchanged.
Exercise
A teammate writes const next = items.with(items.indexOf(target), replacement);. The code works in testing but sometimes corrupts the last item in production. Explain why, and rewrite the line safely.
Show answer
When target is not in items, indexOf returns -1. with treats -1 as the last element, so it replaces that element and raises no error. A safe version is: const i = items.indexOf(target); const next = i === -1 ? items : items.with(i, replacement);. This returns the original array when there is nothing to replace.
Exercise
Why does [].with(0, "x") throw, while [].toSpliced(0, 0, "x") returns ["x"]?
Show answer
with can only replace an existing element, and an empty array has no valid index, so position 0 fails the check 0 <= position < length (0 < 0 is false). toSpliced clamps its start to the range 0 through length and then inserts items at that position. Inserting at position 0 of an empty array is valid and gives a one-element array.