Common Bugs with Loops
Five loop bugs that have eaten more beginner hours than every other category combined.
From Bee: "I see this exact bug in beginners every week. Read it once, and you'll spot it on yourself before it bites."
Off-by-one with <= vs <
js
const xs = [10, 20, 30];
for (let i = 0; i <= xs.length; i++) {
console.log(xs[i]);
}
// 10, 20, 30, undefined⚠️
Why this happens
Indexes go 0, 1, 2 for a length-3 array. i <= 3 runs an extra iteration on a non-existent slot.✅
The fix
Use i < xs.length. Or skip the indexing — use for (const x of xs).Infinite loop — forgot to update the counter
js
let i = 0;
while (i < 5) {
console.log(i);
// forgot i++
}⚠️
Why this happens
Without the increment, the condition stays true forever and the page hangs.✅
The fix
Always update the loop variable inside the body. Modern editors will eventually warn.Modifying the array while looping over it
js
const xs = [1, 2, 3, 4];
for (let i = 0; i < xs.length; i++) {
if (xs[i] % 2 === 0) xs.splice(i, 1);
}
// xs becomes [1, 3, 4] — wrong!⚠️
Why this happens
When you remove element at i, every later element shifts down. The next iteration skips one.✅
The fix
Loop in reverse, or build a new array: xs = xs.filter(n => n % 2 !== 0).Using = where += was meant
js
let total = 0;
for (const p of [10, 20, 30]) {
total = p; // overwrites instead of accumulating
}
// total = 30, not 60⚠️
Why this happens
total = p replaces; total += p accumulates.✅
The fix
Read accumulator code aloud: "for each price, add it to total."break inside the wrong loop
js
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (j === 1) break; // exits inner only!
}
}⚠️
Why this happens
break exits the closest loop. The outer one keeps running.✅
The fix
Use a flag, refactor into a function with return, or use labeled breaks (advanced).💡
Want the full lesson?
Read Loops — the complete lesson, or test yourself with the quiz.