Skip to content

Off-By-One Error

Quick summary

Your loop runs one time too many or too few, or you access an index that is one position off from what you intended.

Why this happens

  • Using <= instead of < in a loop condition (or vice versa)

  • Assuming arrays start at index 1 instead of 0

  • Counting the boundary when you should not (or vice versa)

Minimal example

✗ Broken code
const arr = [1, 2, 3];
for (let i = 0; i <= arr.length; i++) {
  console.log(arr[i]); // arr[3] is undefined!
}
✓ Fixed code
const arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]); // prints 1, 2, 3
}

Using <= includes i = 3, but the array only has indices 0-2. Changing to < stops at i = 2, the last valid index.

How to diagnose

  • Check the loop condition: should it be < or <=?

  • Print the loop variable and the array length to see the actual values

  • Test with a small input where you can manually verify the expected count

How to fix

  • Change <= to < (or < to <=) in the loop condition

  • Use arr.length - 1 when you need the last valid index

  • Prefer for...of or forEach loops that handle bounds automatically

How to prevent

  • Always test loop boundaries with small, verifiable inputs

  • Prefer range-based loops (for...of) over manual index loops

Related Resources

Related Glossary

Related Lessons

  • Loops

    Learn how loops work and avoid off-by-one errors.

← Back to language