Debugging
Overview
Every developer writes bugs. The skill is finding them quickly. Debugging is detective work: you gather clues until the cause is obvious, rather than changing code at random and hoping.
There are two kinds of bug:
- Errors — the code crashes, and the console shows a red message. These are usually the easier kind, because the message tells you where to look.
- Wrong behaviour — no error, but the result is wrong: a total is off, a button does nothing. For these you need to inspect values as the code runs.
Read the error message
Start with the error message: it names the problem and the stack trace lists the file and line where it happened.
TypeError: Cannot read properties of undefined (reading 'title')
at showCourse (app.js:14:22)
at init (app.js:3:3)Line 14 is trying to read .title from something that is undefined. The question to ask is now precise: why is that value undefined? Perhaps an array index is out of range, an API returned a different shape than expected, or a property name has a typo.
Common messages decoded
| Message | Usually means |
|---|---|
x is not defined |
Typo in a name, or the variable is out of scope |
Cannot read properties of undefined (reading 'y') |
something.y where something is undefined — check what came before the dot |
x is not a function |
Calling something that isn’t a function: typo, or a missing method |
Assignment to constant variable |
Reassigning a const — use let |
Unexpected token |
A syntax mistake — missing bracket, comma or quote near that spot |
Unexpected end of JSON input |
Parsing an empty or cut-off response |
Console helpers
console.log('value:', value);
console.table([{ title: 'Loops', done: true }, { title: 'Arrays', done: false }]);
console.dir(document.body); // explore an object’s properties
console.warn('Deprecated option'); // yellow
console.error('Failed to save'); // red
console.time('load'); /* … */ console.timeEnd('load');
console.count('render'); // how many times this line ran
console.trace(); // print the call stack from hereLog with labels.
console.log({ user, total })prints the variable names alongside the values.
Logging objects
The console shows a live view of objects: if the object changes after you log it, expanding it later shows the new values. To capture a snapshot, log a copy:
console.log(structuredClone(cart));
console.log(JSON.stringify(cart, null, 2));Breakpoints
console.log means editing code and reloading each time. Breakpoints let you pause the running code and look around.
In your browser’s developer tools, open the Sources (or Debugger) panel, open your file and click a line number. When the code reaches that line it pauses, and you can:
- hover over variables to see their values,
- look at the Scope pane to see every variable that’s currently visible,
- Step over to run the next line,
- Step into to follow a function call,
- Step out to finish the current function and return to its caller,
- Resume to run until the next breakpoint,
- watch the Call stack to see how you got there.
You can also pause from code:
function checkout(cart) {
debugger; // pauses here when dev tools are open
return cart.total;
}More powerful breakpoints
Right-click a line number for extra options:
- Conditional breakpoint — pause only when an expression is true, such as
i === 99in a long loop. - Logpoint — print a message without pausing, and without editing your code.
The Sources panel can also pause automatically on exceptions, stopping right at the line that throws, with all the variables still available.
Debugging network requests
When data from a server looks wrong, open the Network panel and reload. Click a request to see:
- the status (200, 404, 500…),
- the request you sent (URL, method, headers, body),
- the response the server returned.
This quickly tells you whether the problem is in your request, on the server, or in how your code reads the response.
A simple process
- Reproduce the bug reliably. Note the exact steps and input.
- Locate the first place where a value is not what you expected. Work backwards from the symptom, or use logs to split the code in half and see which half is wrong.
- Understand why. Explaining the code line by line — even to a rubber duck on your desk — often reveals the problem.
- Fix that cause, not just the symptom.
- Verify the fix with the original steps, then remove your
console.loganddebuggerlines.
Change one thing at a time. If you change three things and the bug disappears, you won’t know which one fixed it — or whether the other two broke something else.
Find the bug
This function should return the average score, but it returns the wrong number. Use console.log or a breakpoint to find out why, then fix it.
function average(scores) {
let total = 0;
for (let i = 1; i < scores.length; i++) {
total += scores[i];
}
return total / scores.length;
}
average([10, 20, 30]); // should be 20// The loop started at index 1, so the first score was skipped.
function average(scores) {
let total = 0;
for (let i = 0; i < scores.length; i++) {
total += scores[i];
}
return total / scores.length;
}Summary
- Read the error message and stack trace first — they point to the line.
console.log,console.tableandconsole.dirshow what values really are.- Breakpoints pause code so you can inspect variables and step through it line by line.
- Find the first place a value goes wrong, and fix the cause, not the symptom.
- The Network panel shows every request — essential for fetch bugs.