Spot the Off-by-One Error
Question
This loop is supposed to print all elements of a 3-element array but skips the last one. What is wrong?
Code
const arr = [10, 20, 30];
for (let i = 0; i < arr.length - 1; i++) {
console.log(arr[i]);
}
Hint
Array indices go from 0 to length-1. The loop condition should allow i to reach length-1.
Explanation
With i < arr.length - 1 (i.e., i < 2), the loop runs for i = 0 and i = 1, printing 10 and 20, but skips i = 2 (the last element, 30). The correct condition is i < arr.length (i.e., i < 3), which runs for i = 0, 1, 2 — all three elements. This is a classic off-by-one error.
Related Resources
Related Lessons
- Loops
Learn about loop boundaries.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.