Skip to content

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

✗ Broken code
const arr = [1, 2, 3];
console.log(arr[5]);
✓ Fixed code
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 0 to length - 1?

  • Verify the array is not empty before accessing elements

How to fix

  • Check index < array.length before accessing the element

  • Fix the loop boundary to use < instead of <=

  • Use safe access methods like array.at(index) or try/except

How to prevent

  • Prefer for...of or for-each loops over manual index loops

  • Validate the index against the array length before access

Related Resources

Related Glossary

Related Lessons

  • Arrays

    Learn how arrays work in programming

Related Practice

← Back to language