Sub topic 7
Negative indices and out-of-range errors
This chapter assumes you know how to index arrays with brackets and how with(index, value) returns a copy with one element replaced. Here we look at the index rules that with follows. They differ from bracket assignment in ways that matter when the index comes from user input or a calculation.
How `with` reads an index
with uses relative indexing, the same rule as Array.prototype.at. A non-negative index counts from the start. A negative index counts back from the end, so -1 is the last element, -2 the one before it, and so on. Internally the method adds length to a negative index before using it.
const values = [10, 20, 30, 40];
console.log(values.with(-1, 99)); // [10, 20, 30, 99]
console.log(values.with(-4, 99)); // [99, 20, 30, 40]
console.log(values.at(-2)); // 30
console.log(values); // [10, 20, 30, 40]For an array of length n, the valid indices run from -n to n - 1. Anything outside that range throws a RangeError.
Bracket assignment behaves differently
Bracket assignment never throws for a bad index. It quietly does something else, which is where bugs hide.
const a = [1, 2, 3];
a[5] = 0;
console.log(a.length); // 6, with holes at indices 3 and 4
const b = [1, 2, 3];
b[-1] = 0;
console.log(b); // [1, 2, 3, "-1": 0] in Node; the array is unchanged
console.log(b.length); // 3a[5] = 0 grows the array and leaves holes. b[-1] = 0 creates an ordinary property named "-1" that no array method sees. with rejects both cases:
const c = [1, 2, 3];
for (const i of [3, 5, -4]) {
try {
c.with(i, 0);
} catch (err) {
console.log(i, err instanceof RangeError); // true for each
}
}The two methods differ in one more way. at returns undefined for an out-of-range index, while with throws. Reading past the end is harmless, but writing past the end usually means your index logic is wrong, so with fails loudly.
| Operation | Index `-1` on `[1, 2, 3]` | Index `5` on `[1, 2, 3]` |
|---|---|---|
| `arr[i] = x` | Adds property `"-1"` | Grows array to length 6 |
| `arr.at(i)` | Returns `3` | Returns `undefined` |
| `arr.with(i, x)` | Replaces last element | Throws `RangeError` |
Index conversion gotchas
Before the range check, with converts the index to an integer. Fractions are truncated toward zero, numeric strings are parsed, and NaN or undefined become 0.
const d = ["a", "b", "c"];
console.log(d.with(1.9, "x")); // ["a", "x", "c"]
console.log(d.with("2", "x")); // ["a", "b", "x"]
console.log(d.with(undefined, "x")); // ["x", "b", "c"]A common error is arr.with(arr.indexOf(item), newItem) when item is not in the array. indexOf returns -1, which is a valid relative index, so the last element gets replaced. Check for -1 first:
function replaceItem(arr, item, next) {
const i = arr.indexOf(item);
return i === -1 ? arr : arr.with(i, next);
}
console.log(replaceItem(["x", "y"], "z", "w")); // ["x", "y"]
console.log(replaceItem(["x", "y"], "y", "w")); // ["x", "w"]An empty array has no valid index at all, so [].with(0, 1) and [].with(-1, 1) both throw.
Exercise
Given const list = ["p", "q", "r"];, what does each expression produce: list.with(-3, "z"), list.with(3, "z"), and list.with(list.indexOf("missing"), "z")?
Show answer
list.with(-3, "z") returns ["z", "q", "r"] because -3 + 3 = 0. list.with(3, "z") throws a RangeError because 3 is not less than the length. list.with(list.indexOf("missing"), "z") returns ["p", "q", "z"]: indexOf gives -1, which resolves to the last index. That is a silent bug unless you check for -1 first.
Exercise
Why does arr[-1] = 0 not change the last element, while arr.with(-1, 0) does?
Show answer
Bracket assignment treats -1 as the property key "-1", which is not an array index, so it adds a separate property. with uses relative indexing and adds length to negative values, so -1 refers to the last element.