Debugging
Finding bugs fast.
Every programmer writes bugs. Good programmers find them quickly. The trick isn't guessing. It's reading the error, checking your assumptions, and narrowing down where things go wrong.

- Everyone writes bugs
- Find them quickly
- Read, check, narrow down
Reading an error
This function should total the prices, but it crashes. The error tells us the type, a type error, and the message, cannot read properties of undefined. The cause is the loop. It uses less than or equal, so it reads one item past the end of the array. Run it.
const cart = [{ price: 5 }, { price: 8 }, { price: 2 }];
function total(items) {
let sum = 0;
for (let i = 0; i <= items.length; i++) {
sum += items[i].price;
}
return sum;
}
try { console.log(total(cart)); }
catch (e) { console.log(e.name + ":", e.message); }TypeError: Cannot read properties of undefined (reading 'price')
console tools
Console dot table shows arrays of objects as a neat table, which is great for checking data. Console dot error prints in red in most tools. And console dot time and time end measure how long code takes. Run it.
const users = [
{ name: "Ana", age: 29 },
{ name: "Ben", age: 34 },
];
console.table(users);
console.time("loop");
let n = 0;
for (let i = 0; i < 1e6; i++) n += i;
console.timeEnd("loop");┌─────────┬───────┬─────┐ │ (index) │ name │ age │ ├─────────┼───────┼─────┤ │ 0 │ 'Ana' │ 29 │ │ 1 │ 'Ben' │ 34 │ └─────────┴───────┴─────┘ loop: 2.858ms
A debugging routine
First, read the whole error, including the line number. Second, reproduce the bug with the smallest input you can. Third, log values, or use the debugger in your browser's developer tools, to see what's really happening. Then fix one thing at a time, and check again.
| key | value |
|---|---|
| 1. Read | name, message, line |
| 2. Reproduce | smallest input |
| 3. Inspect | console.log, debugger |
| 4. Fix | one change at a time |
Summary
Read errors carefully, reproduce the bug, and inspect values with console tools or the debugger. Next, writing clean code that has fewer bugs to begin with.
Key takeaways- Read the error
- console.table / time
- Narrow it down