Module 26: Debugging and Testing

Lesson 2 of 5 · 15–25 minutes

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:

  1. Reproduce it reliably. Write down the exact input and steps.
  2. Shrink the problem: remove everything not needed to cause it. A small example often reveals the cause on its own.
  3. Read the error and stack trace, from the first line that mentions your own code.
  4. Check assumptions with console.log or the debugger: is the value what you think it is, and the type? (typeof, and Array.isArray.)
  5. One change at a time, and retest after each.
  6. Write a test that fails because of the bug (Lesson 4), then fix it. The test stops it coming back.

Also useful:

🖱️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.

← PreviousThrowing and catching errors
ProLearners Assist