Common Bugs with Loops

📌 Common bugs · loops✍️ Written by Mark Sullivan📅 Reviewed 2026-04-25⏱ ~7 min read

Five loop bugs that have eaten more beginner hours than every other category combined.

Bee mascot
From Bee: "I see this exact bug in beginners every week. Read it once, and you'll spot it on yourself before it bites."
#1

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).
#2

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.
#3

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).
#4

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."
#5

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.

M
Mark Sullivan
Lead writer · 8 yrs full-stack

Mark started coding in 2017 after switching from financial analysis. She's built production systems in Python (Django) and JavaScript (Node + React) at two startups, and has taught intro programming at his local community college since 2022. He owns the curriculum for variables, functions, conditionals, and loops on this site. More about Mark →