Skip to content

Incorrect Loop Boundary

Quick summary

Your loop starts at the wrong index or ends at the wrong condition, causing it to skip elements or process extra ones.

Why this happens

  • Starting the loop at 1 instead of 0 (or vice versa)

  • Using the wrong comparison operator (< vs <=)

  • Using length instead of length - 1 for the last index

Minimal example

✗ Broken code
const arr = [10, 20, 30, 40, 50];
let sum = 0;
for (let i = 1; i < arr.length; i++) { // Skips first element!
  sum += arr[i];
}
console.log(sum); // 120, should be 150
✓ Fixed code
const arr = [10, 20, 30, 40, 50];
let sum = 0;
for (let i = 0; i < arr.length; i++) { // Starts at 0
  sum += arr[i];
}
console.log(sum); // 150

Starting at i = 1 skips the first element (arr[0] = 10). Starting at i = 0 includes all elements, giving the correct sum of 150.

How to diagnose

  • Print the loop variable at each iteration to see the actual range

  • Compare the number of iterations with the expected count

  • Test with a small array where you can verify each step

How to fix

  • Adjust the start value or end condition

  • Change < to <= or vice versa

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

How to prevent

  • Test loops with small, verifiable inputs

  • Prefer for...of loops that handle boundaries automatically

Related Resources

Related Glossary

Related Lessons

  • Loops

    Learn about loop boundaries.

← Back to language