Most loop bugs don't crash. They hand back a number that is slightly wrong, and the code looks fine when you read it top to bottom.
Reading loops like prose is the problem. A loop is a small machine: some variables, a question asked before every turn, and a few lines that change the variables. If you keep a little table of those variables and update it line by line, the bug usually shows up on its own.
This post covers five bugs I see over and over in beginner code. Each one has:
- a short snippet with the bug,
- a Predict before running prompt (do it on paper, it takes a minute),
- the mental model that explains it,
- a lab: the broken function, opened in a step-through visualizer, where you fix it and get checked against hidden cases.
The labs use Code Glyphs, a browser step-through tool I built. You don't need it to follow along: every snippet below is plain JavaScript you can paste into Node or the browser console. But watching the variables change one step at a time is the fastest way I know to build the habit.
How the labs work. Each lab opens with the broken function already loaded. Press Step to advance one stroke at a time and watch the values change, or Run to go straight to the result. Edit the shape (or the JavaScript pane), then press Check my shape. It runs your fix on the cases shown and on some hidden ones. Opening a lab link never runs anything until you press a button. A small vocabulary note: Code Glyphs calls variables "wells" and loops "rings". It's the same thing you already know.
If the embedded labs don't load where you're reading this, every lab also has a plain link right under it.
Bug 1: Off by one, the loop stops an item early
function total(prices) {
let sum = 0;
for (let i = 0; i < prices.length - 1; i += 1) {
sum += prices[i];
}
return sum;
}
total([4, 8, 15]);
Predict before running. Write down i and sum after every turn. What does total([4, 8, 15]) return? What should it return?
What happens. It returns 12, not 27. The list has 3 items, so prices.length - 1 is 2, and the condition i < 2 lets i be 0 and 1 only. Index 2 (the 15) is never visited.
The mental model. A loop condition is a question asked before every turn: "may I take another turn?" To visit every item, the last turn must be the one where i is length - 1, and the first refusal must be i === length. So the question is i < prices.length.
Off-by-one bugs come in three flavours, and all three are the same mistake about where the fence ends:
| You wrote | What it does on [4, 8, 15]
|
|---|---|
i < prices.length - 1 |
skips the last item, returns 12
|
i <= prices.length |
reads prices[3], which is undefined, so the sum becomes NaN
|
for (let i = 1; i < n; i += 1) to add 1..n
|
never adds n: n = 4 gives 6, not 10
|
A quick check that works for all of them: take the smallest case that matters (a list of 1 item, or n = 1) and ask "which i values run?" out loud.
Lab: fix total. The starting shape is the code above. Case 1 is the list you just traced.
Bug 2: Overwriting an accumulator (= instead of +=)
function sumPositive(nums) {
let total = 0;
for (const n of nums) {
if (n > 0) {
total = n;
}
}
return total;
}
sumPositive([3, -1, 4, 2]);
Predict before running. Track total for each item of [3, -1, 4, 2]. What comes back?
What happens. 2: the last positive number. total = n doesn't add anything, it replaces the old value with the current item, every time. The correct answer is 9.
The mental model. An accumulator has to read itself. total += n means total = total + n: the right-hand side uses the old value. When you review a loop that builds up a result, ask one question of the line that updates it: does the right-hand side mention the variable on the left? If not, you are replacing, not accumulating.
The same bug has a cousin: writing let total = 0 inside the loop body. That creates a fresh total on every turn, so each pass starts from zero again. Declare accumulators before the loop, update them inside.
Also notice how this one hides. For [-5, -2] the broken version returns 0, which happens to be right. A test with a single example can pass while the bug is still there.
Lab: fix sumPositive.
Bug 3: Returning too early
function allPass(scores) {
for (const s of scores) {
if (s >= 60) {
return true;
} else {
return false;
}
}
return true;
}
allPass([80, 45, 90]);
Predict before running. How many items does the loop look at before the function ends? What does allPass([80, 45, 90]) return?
What happens. It looks at exactly one item. 80 passes, so it returns true and the function is over. The 45 is never examined. (Swap the first score for a failing one and it returns false just as quickly, so the answer depends only on the first item.) Expected: false.
The mental model. return ends the whole function, not just the current turn. Inside a loop, every return is a claim: "I now know the final answer." So before writing it, ask whether this one item really settles the question.
For "do all items pass?", the answer is:
- one failure settles it (
return falseinside the loop), - one success settles nothing (you have to see the rest),
- so
return truegoes after the loop.
The pattern flips for "does any item fail?", and it's the same shape for "find the first match":
| Question | Settled early by | After the loop |
|---|---|---|
| Do all items pass? | the first failure, return false
|
return true |
| Does any item fail? | the first failure, return true
|
return false |
| Find the first item that matches | the first match, return item
|
"not found" value |
An if with a return in both branches inside a loop body is almost always this bug.
Lab: fix allPass. Watch how few steps the broken version takes, then compare with your fix.
Bug 4: Starting min or max at 0
function largest(temps) {
let max = 0;
for (const t of temps) {
if (t > max) {
max = t;
}
}
return max;
}
largest([-4, -9, -2]);
Predict before running. Run it by hand on [-4, -9, -2], then on [3, 8, 5]. Do both come out right?
What happens. [3, 8, 5] gives 8, which is correct, so the function looks fine on the first thing you try. [-4, -9, -2] gives 0 instead of -2. No item is bigger than 0, so max never changes and the 0 you invented is returned. It isn't even in the list.
The mirror image: let min = 0 on [7, 12, 9] returns 0, a value that was never in the data.
The mental model. The starting value of an accumulator must be one that can't affect the result. For a sum that's 0, for a product it's 1. For "biggest so far" there is no such number in the data, because any number you pick (like 0) can win against the real items. The safe start is an actual item: let max = temps[0].
(In plain JavaScript you can also start at -Infinity, or use Math.max(...temps). The lab asks for the first-item version, and its checker rejects Infinity, because it only accepts plain pieces.)
Decide what an empty list means before you write this. temps[0] on [] is undefined, and that might be exactly the answer you want, or a bug to handle.
Lab: fix largest.
Bug 5: A condition that never allows a turn (or never stops)
function sumDown(n) {
let total = 0;
let i = n;
while (i < 1) {
total += i;
i -= 1;
}
return total;
}
sumDown(4);
Predict before running. How many times does the loop body run for n = 4? What comes back?
What happens. Zero turns, and it returns 0. The condition is checked before the first turn: i starts at 4, 4 < 1 is false, and the loop is skipped entirely. Expected: 10.
The mental model. A while loop needs three things to agree:
- a start value,
- a condition that is true while there is work left,
- a step that moves toward making the condition false.
Two ways to break that agreement:
- the condition is false at the start, so the body runs zero times (this lab),
- the step moves away from making it false, so the loop never ends.
Both can come from the same one-character mistake. Try this: in the broken sumDown, give it n = 0. Now i starts at 0, 0 < 1 is true, and each turn makes i smaller, which keeps it below 1 forever. The lab's interpreter stops it with "This ring never ends. Stopped after 300,000 steps". In a real browser tab or Node process there is no such safety net, so don't run an unfinished while loop in the console unprepared.
Checklist for any while: Is the condition true on the first check? Does every turn push it closer to false? Say it out loud with the real numbers.
Lab: fix sumDown. Step through sumDown(4) and watch the loop get skipped. Then step through the same shape with n = 0 in the Run panel to see it run away.
Practice: count the turns
One more thing to try, a read-only puzzle from the free tier. You don't write any code: you predict how many times a loop body runs.
Turns of the ring: sum from 1 by 1s, below height: read the condition carefully, count on paper, then answer.
A 60-second loop review
Before you run a loop you wrote, take the smallest interesting input and answer these five questions on paper:
- Which values does the loop variable take? Is the first one included, the last one?
- Does every line that builds up a result read the variable it updates?
- Is each
returninside the loop really settled by this one item? - Does the starting value of the result belong to the data, or can it win by accident?
- Is the loop condition true on the first check, and does every turn move it toward false?
If you want to share a lab with a student or a teammate, it's all in the link: the task, the cases and the starting code. Your fix is never part of it.
Top comments (0)