AK/Wri/Off By One Field Guide

Off-by-one field guide

1 min read

fence post — counting posts vs gaps. ten meters of fence with posts every meter needs 11 posts, not 10. loops that use range(n) when they needed range(n + 1) live here.

slice end is exclusive — arr[0:3] is indices 0,1,2. python, js, rust agree. your brain wants inclusive ends because human language does.

PYTHON
page = items[0:10]   # first ten items
# not items[0:9]

1-based UI, 0-based code — design shows page 1. api expects offset = (page - 1) * size. forgetting the - 1 ships page 2 on first click.

TYPESCRIPT
const offset = (page - 1) * pageSize;

< length vs <= length — classic loop exit. one wrong symbol, infinite loop or early stop.

TYPESCRIPT
for (let i = 0; i < ids.length; i++) { /* safe */ }
for (let i = 0; i <= ids.length; i++) { /* oops */ }

pagination total pages — Math.ceil(count / size), not Math.floor. nine items at size 10 still needs one page.

binary search bounds — while (lo < hi) vs <=, mid = lo + (hi - lo) / 2, and whether hi is inclusive. pick a style, comment it, never mix two styles in one repo.

date ranges — "last 7 days" often means seven 24-hour buckets, not today - 7 at midnight boundaries. timezone turns this into a seasonal sport.

array.splice after filter — mutating while iterating by index. remove one item, indices shift, you skip the next one. walk backwards or rebuild.


i still grep for <= length and range(len before release. the bugs are never new. only the variable names change.