Module 26: Debugging and Testing
A debugging method
🏠The everyday picture
A doctor doesn't prescribe at random. They ask about symptoms, examine, form a diagnosis, test it, and only then treat. Debugging is the same discipline.
📘What it really is
Building on Module 20:
- Reproduce it reliably. Write down the exact input and steps.
- Shrink the problem: remove everything not needed to cause it. A small example often reveals the cause on its own.
- Read the error and stack trace, from the first line that mentions your own code.
- Check assumptions with
console.logor the debugger: is the value what you think it is, and the type? (typeof, andArray.isArray.) - One change at a time, and retest after each.
- Write a test that fails because of the bug (Lesson 4), then fix it. The test stops it coming back.
Also useful:
-
Rubber duck debugging: explain the code out loud, line by line, to anyone or anything. You'll often hear the mistake yourself.
-
Node's debugger:
node --inspect-brk file.js, then openchrome://inspectin Chrome to use the same breakpoint tools as in Module 20. -
With AI: give it the smallest example that shows the problem, the full error, what you expected, and what you've already ruled out.
🖱️Try it
Here's a buggy function. Use the method above to find and fix the bug:
function averagePrice(products) {
let total = 0;
for (let i = 1; i < products.length; i++) {
total += products[i].price;
}
return total / products.length;
}
(Try it with two products priced 100 and 200. What should the answer be? What is it?)
✅Quick check
Why shrink a bug down to a small example?
Show the answer
Fewer moving parts make the cause easier to see, and a small example is easier to share with someone or an AI.
What's the bug in averagePrice?
Show the answer
The loop starts at 1, skipping the first product. It should start at 0 (or use for...of). Also, an empty list
divides by zero, which needs handling.
