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++)`.
- 1Pass 1 · i = 0 (0 < 2 is true)
- 2Pass 2 · i = 1 (1 < 2 is true)
- 3Stop check · i = 2 (2 < 2 is false)
- 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.
| Case | State after the step |
|---|---|
| Pass 1 · i = 0 (0 < 2 is true) | — |
| Pass 2 · i = 1 (1 < 2 is true) | — |
| Stop check · i = 2 (2 < 2 is false) | — |
Reveal the explanation
- Pass 1 · i = 0 (0 < 2 is true)
Checks key[0] ("A") == answers[0] ("A") → score becomes 1.
- Pass 2 · i = 1 (1 < 2 is true)
Checks key[1] ("B") == answers[1] ("B") → score becomes 2.
- 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.
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
This browser could not save your progress. Changes last until you leave the page.