Common Bugs with Arrays
Off-by-one and shared-reference bugs are why arrays cost beginners hours. Here are the five worst offenders.
From Bee: "I see this exact bug in beginners every week. Read it once, and you'll spot it on yourself before it bites."
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.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].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).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.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.