Classic Off-by-One Errors
You'll learn to spot and avoid the frustrating boundary mistakes that cause loops to run one time too many or too few.
What Are Off-by-One Errors?
An off-by-one error happens when your loop runs one iteration more or less than intended. These bugs are called "fence-post errors" after the classic puzzle: If you need to build a 10-meter fence with posts every meter, how many posts do you need? The answer is 11 (one at each end plus nine in between)—not 10!
Common Off-by-One Mistakes
Starting at 1 Instead of 0
Arrays are zero-indexed, but beginners often start counting at 1:
let items = ['a', 'b', 'c'];
for (let i = 1; i < items.length; i++) {
// Skips items[0]! Starts at 'b' instead of 'a'
}
Using <= Instead of <
for (let i = 0; i <= items.length; i++) {
// Runs 4 times for 3 items
// items[3] is undefined!
}
Counting Down Incorrectly
for (let i = items.length; i >= 0; i--) {
// Runs 4 times when items.length is 3
// First iteration: items[3] is undefined
}
The correct version: let i = items.length - 1
How to Avoid Them
- Remember arrays start at 0 and end at
length - 1 - Use
<not<=when comparing tolength - Initialize counters at 0 unless you have a specific reason not to
- Test boundary cases: run your loop with an array of length 0, 1, and 2
Key Takeaway: Off-by-one errors happen at loop boundaries—always double-check your starting index, ending condition, and whether you're including or excluding the final value.