Common Bugs with Arrays

📌 Common bugs · arrays✍️ Written by Tom Reyes📅 Reviewed 2026-04-14⏱ ~7 min read

Off-by-one and shared-reference bugs are why arrays cost beginners hours. Here are the five worst offenders.

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

Index out of bounds

py
xs = [10, 20, 30]
print(xs[3])   # IndexError
⚠️
Why this happens
Last valid index is length - 1. xs[3] is past the end.
The fix
Use xs[-1] for the last item in Python, or xs[xs.length - 1] in JS/Java.
#2

Negative indexes that don't mean what you think

js
const xs = [10, 20, 30];
console.log(xs[-1]);  // undefined
⚠️
Why this happens
JavaScript doesn't support negative indexing. Python does.
The fix
Use xs.at(-1) in modern JS, or xs[xs.length-1].
#3

Mutation during iteration

js
const xs = [1, 2, 3, 4];
xs.forEach((n, i) => {
  if (n % 2 === 0) xs.splice(i, 1);
});
⚠️
Why this happens
Same as the loops bug — modifying during iteration causes skips.
The fix
xs = xs.filter(n => n % 2 !== 0).
#4

Sharing a reference instead of copying

js
const original = [1, 2, 3];
const copy = original;   // NOT a copy
copy.push(99);
console.log(original);   // [1, 2, 3, 99]
⚠️
Why this happens
copy = original aliases. Both names point to the same array.
The fix
const copy = [...original] for a real (shallow) copy.
#5

sort() returning unexpected order

js
console.log([10, 2, 1].sort());
// [1, 10, 2] — sorts as strings by default!
⚠️
Why this happens
JS's default sort coerces to strings. "10" comes before "2" alphabetically.
The fix
Pass a comparator: arr.sort((a, b) => a - b).
💡
Want the full lesson?

Read Arrays — the complete lesson, or test yourself with the quiz.

T
Tom Reyes
Reviewer · 12 yrs Java/JVM

Tom spent eight years as a backend engineer in fintech (Java + Kotlin) and four as a lead at an enterprise SaaS company. He reviews every Java example on this site and writes the data-structure deep dives. He cares deeply that beginners aren't taught bad habits they'll have to unlearn. More about Tom →