Index Out of Range
Quick summary
You tried to read or write a position in an array that is outside its valid range of indices.
Why this happens
Index is greater than or equal to the array length
The array is empty but was accessed at index 0
Off-by-one error in a loop boundary (e.g.,
<=instead of<)
Minimal example
const arr = [1, 2, 3];
console.log(arr[5]);const arr = [1, 2, 3];
console.log(arr[2]);arr[5] is out of range — the array has only 3 elements (indices 0–2), so arr[2] accesses the last valid element.
How to diagnose
Print the array length and the index being accessed
Check loop bounds — does the index stay within
0tolength - 1?Verify the array is not empty before accessing elements
How to fix
Check
index < array.lengthbefore accessing the elementFix the loop boundary to use
<instead of<=Use safe access methods like
array.at(index)ortry/except
How to prevent
Prefer
for...oforfor-eachloops over manual index loopsValidate the index against the array length before access
Related Resources
Related Lessons
- Arrays
Learn how arrays work in programming
Related Practice
- Identify the Data Type
Practice recognizing data types used in indexing.