AI Hints
Home›JavaScript Tutorial›Debugging and Clean Code
JavaScript · Lesson 112 of 138

Debugging

Finding bugs fast.

⏱ 2 min read▶ Video at 2:14:50🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Debugging
From the video: Debugging
  • 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.

app.jsjavascript
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); }
Output
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.

app.jsjavascript
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");
Output
┌─────────┬───────┬─────┐
│ (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.

keyvalue
1. Readname, message, line
2. Reproducesmallest input
3. Inspectconsole.log, debugger
4. Fixone 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
Next up: Clean Code — code people can read