Script Valley
Debugging: A Systematic Approach
Reading Code to Find BugsLesson 2.2

How boundary conditions cause most logic bugs

boundary conditions, off-by-one errors, empty input, null values, integer overflow, edge case enumeration

Boundaries Break Code

The majority of logic bugs occur at the edges of valid input ranges, not in the middle. Arrays at index 0 and length-1. Loops that run zero times. Null inputs to functions that assume non-null. Knowing boundary conditions exist is not enough -- you must actively test them.

The Boundary Checklist

For any function, enumerate these cases before testing: empty input (empty array, empty string, zero), single element input, maximum valid input, minimum valid input, and input just outside valid bounds. For loops: does it run correctly when the list has 0 items? 1 item? 2 items?

function firstPositive(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > 0) return arr[i];
  }
  // Bug: returns undefined when no positive exists
  // Fix: return null or throw, never implicit undefined
}

// Boundary tests:
console.log(firstPositive([]));       // undefined -- boundary failure
console.log(firstPositive([-1,-2]));  // undefined -- boundary failure
console.log(firstPositive([0]));      // undefined -- 0 not positive, correct
console.log(firstPositive([1]));      // 1 -- correct

Off-By-One Is Its Own Category

Off-by-one errors are so common they deserve explicit attention. Every time you write less-than vs less-than-or-equal in a loop, stop and ask: should the last index be included? Write the boundary value in a comment next to the condition. This single habit eliminates a large class of bugs.

Up next

How to spot common JavaScript and Python bug patterns

Sign in to track progress

How boundary conditions cause most logic bugs โ€” Reading Code to Find Bugs โ€” Debugging: A Systematic Approach โ€” Script Valley โ€” Script Valley