Off-by-One Error
ELI5 — The Vibe Check
An off-by-one error is when you're exactly one too many or one too few — the most common bug in programming. Is it < or <=? Does the array start at 0 or 1? Should the loop run 10 times or 11? There are two hard problems in computer science: cache invalidation, naming things, and off-by-one errors.
Real Talk
An off-by-one error (OBOE) occurs when a loop iterates one time too many or too few, or when an index is one position off. Common causes: confusing inclusive vs exclusive bounds, zero-based vs one-based indexing, and fence-post errors (n items have n-1 gaps). It's the most frequent bug category in software and the punchline of a famous computer science joke.
Show Me The Code
// Off-by-one: fence post problem
// Building a fence 100m long with posts every 10m
// Wrong: 100/10 = 10 posts
// Right: 100/10 + 1 = 11 posts (need one at each end)
// Off-by-one: array access
const arr = [1, 2, 3, 4, 5]
for (let i = 0; i <= arr.length; i++) { // Bug: <= should be <
console.log(arr[i]) // arr[5] is undefined!
}
When You'll Hear This
"Classic off-by-one — the loop should be < not <=." / "The two hardest problems in CS: cache invalidation, naming things, and off-by-one errors."
Related Terms
Array
An array is a list of things in order, like a numbered row of boxes. Box 0 holds the first item, box 1 holds the second, and so on.
Bug
A bug is anything in your code that makes it behave wrong.
Edge Case
Edge cases are the weird, extreme, or unexpected inputs that trip up your code. What if someone types 0 for age?
Loop
A loop makes your code do something over and over until a condition says stop.