krahets/hello-algo · error · Error
Index out of bounds
Error message
Index out of bounds
What it means
Thrown by MyList.get() (JavaScript, private-field variant) when index < 0 or index >= #size. The bounds use the logical element count (#size), not the allocated capacity. This is the read accessor; it fails fast rather than returning undefined, which is the JS-idiomatic but silent alternative.
Source
Thrown at en/codes/javascript/chapter_array_and_linkedlist/my_list.js:32
/* Constructor */
constructor() {
this.#arr = new Array(this.#capacity);
}
/* Get list length (current number of elements) */
size() {
return this.#size;
}
/* Get list capacity */
capacity() {
return this.#capacity;
}
/* Update element */
get(index) {
// If the index is out of bounds, throw an exception, as below
if (index < 0 || index >= this.#size) throw new Error('Index out of bounds');
return this.#arr[index];
}
/* Add elements at the end */
set(index, num) {
if (index < 0 || index >= this.#size) throw new Error('Index out of bounds');
this.#arr[index] = num;
}
/* Direct traversal of list elements */
add(num) {
// If length equals capacity, need to expand
if (this.#size === this.#capacity) {
this.extendCapacity();
}
// Add new element to end of list
this.#arr[this.#size] = num;
this.#size++;View on GitHub (pinned to 69932aed18)
Solutions
- Validate before access: if (index >= 0 && index < list.size()) list.get(index).
- Use < size() (not <=) for loop upper bounds.
- Recompute size after mutations that shrink the list.
Example fix
// before const v = list.get(list.size()); // throws Index out of bounds // after const v = (index >= 0 && index < list.size()) ? list.get(index) : undefined;
Defensive patterns
Strategy: validation
Validate before calling
function safeGet(list, index) {
return (index >= 0 && index < list.size()) ? list.get(index) : undefined;
} Type guard
null
Try / catch
null
Prevention
- Validate index against size() before get.
- Use < size() (not <=) for loop bounds.
- Recompute size after removals.
- Remember negative indices do NOT wrap (unlike Python).
When it happens
Trigger: Calling get(index) with a negative index, an index >= current size, or on an empty list (any index).
Common situations: Off-by-one loop bounds (<= vs <); reading an index captured before a remove shrank the list; confusing size() with capacity(); porting from an API where negative indices wrap (Python-style).
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/8185f974479f2642.
Report an issue: GitHub.