Common bug patterns
Recognize common bugs like off-by-one, undefined access and wrong comparison.
The off-by-one error
An off-by-one error comes from a boundary being one too few or one too many. It most often appears when <= is written instead of < (or the other way). For example, for (let i = 0; i <= arr.length; i++) walks the array one step too far and reaches arr[arr.length], which is undefined.
The correct form is usually i < arr.length. Always think about whether the boundary condition should include equality.
Undefined access and wrong comparison
Two other common bugs: undefined access and wrong comparison. When you access a property that does not exist on an object you get undefined; operating on it throws a TypeError. Check that it exists first.
The == operator coerces types and can surprise you (0 == "" is true). If the type matters too, use ===. It does not mislead equality.
Exercise Fix the boundary error
Define a function called sumFirst(nums, k). It should sum and return the first k elements of the array. Use a for (let i = 0; i < k; i++) loop (use < not <= to avoid off-by-one). Then assign the result of sumFirst([10, 20, 30, 40], 3) to a variable result and log it with console.log(result).
Show example solution
function sumFirst(nums, k) {
let total = 0;
for (let i = 0; i < k; i++) {
total += nums[i];
}
return total;
}
const result = sumFirst([10, 20, 30, 40], 3);
console.log(result);
Test yourself
-
Match the bug pattern
- i <= arr.length
- Walks the array one step too far
- i < arr.length
- Walks the array exactly
- arr[arr.length]
- Is the undefined value
- arr[0]
- Is the first element
-
Which is an off-by-one error?
- for (let i = 0; i <= arr.length; i++)
- for (let i = 0; i < arr.length; i++)
- const first = arr[0]
- console.log(arr)
Show answer
for (let i = 0; i <= arr.length; i++) — Correct. With <= the array is walked one step too far.
-
Add strict equality
if (count ____ 5) { console.log("five"); }Show answer
if (count === 5) { console.log("five"); }