Curriculum

Curriculum

Find and Fix an Off-by-One Loop Bug

Scenario

Scoring `key = ["A", "B", "C"]` against `answers = ["A", "B", "C"]` returned 2 instead of 3. Trace the buggy loop `for (i = 0; i < key.length - 1; i++)`.

  1. 1Pass 1 · i = 0 (0 < 2 is true)
  2. 2Pass 2 · i = 1 (1 < 2 is true)
  3. 3Stop check · i = 2 (2 < 2 is false)
Buggy vs Fixed Loop Bounds (JS)
- for (let i = 0; i < key.length - 1; i++) {
+ for (let i = 0; i < key.length; i++) {
    if (key[i] === answers[i]) score += 1;
  }

Try it yourself

Step through each index to see which item is skipped.

Reveal the explanation
  1. Pass 1 · i = 0 (0 < 2 is true)

    Checks key[0] ("A") == answers[0] ("A") → score becomes 1.

  2. Pass 2 · i = 1 (1 < 2 is true)

    Checks key[1] ("B") == answers[1] ("B") → score becomes 2.

  3. Stop check · i = 2 (2 < 2 is false)

    Loop stops! Index 2 ("C") is never checked. Fix bound to `i < key.length`.

Writing an index trace table for a 3-item list immediately exposes whether index 0 or index `length - 1` was missed.

Review first

Your turn

Trace what happens if someone writes `for (i = 0; i <= items.length; i++)` on a 2-item list `["X", "Y"]`.

Common mistake Confusing the last valid index (`length - 1`) with the loop stop condition (`i < length`).

Check your work

Trace showing i=0 ("X"), i=1 ("Y"), and i=2 (`undefined` / index-out-of-range error).

Quick check

For a 4-item zero-indexed list, which loop bound visits indexes 0, 1, 2, and 3 exactly once?
Show the answer and reasoning

Correct answer Start at i = 0; continue while i < list.length

With length 4, `i = 0; i < 4` runs for 0, 1, 2, and 3 and stops cleanly at 4.