Skip to content

Off-by-One Error

Easy — everyone uses thisGeneral Dev

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."

Made with passive-aggressive love by manoga.digital. Powered by Claude.