Debugging with browser DevTools
Course contents (16 lessons)
- Modern syntax
- Destructuring, spread and rest
- ES modules: import and export
- Objects, this and errors
- Classes and prototypes
- Understanding this in JavaScript
- Error handling: try, catch and custom errors
- Asynchronous JavaScript
- The event loop: how JavaScript handles waiting
- From callbacks to promises to async/await
- Fetch and REST APIs
- Working in the browser
- Local storage and session storage
- Debugging with browser DevTools
- Performance basics: debounce and throttle
- Node.js essentials
- Node.js and npm basics
- Working with files in Node.js
- A tiny HTTP server with Node.js
- Testing and the final project
- Testing basics with the Node.js test runner
- Final project: a post explorer with modules and fetch
Stop guessing, start looking
When code does not work, many beginners add console.log everywhere and hope. That can work, but the browser DevTools can show you exactly what is happening, line by line. Open them with F12 or Ctrl+Shift+I (Cmd+Option+I on Mac). This lesson uses Chrome and Edge names, and Firefox has equivalents of everything here.
The Console
The console is more than console.log. There are several useful methods:
const users = [
{ name: "Ali", age: 25 },
{ name: "Sara", age: 31 },
];
console.log("Plain message", users.length);
console.warn("Something looks off");
console.error("Something failed");
console.table(users); // nice table for arrays of objects
console.group("Details");
console.log("Inside the group");
console.groupEnd();
console.time("loop");
for (let i = 0; i < 1e6; i++) {}
console.timeEnd("loop"); // prints elapsed time
console.assert(users.length === 3, "Expected three users");
console.table is the one I wish I had learned earlier. An array of objects becomes a readable grid. In the browser console, you can also click an object to expand it.
One trap: when you log an object and expand it later, the browser shows its current state, not the state at the moment of logging. If you want a snapshot, log a copy: console.log(JSON.parse(JSON.stringify(obj))) or structuredClone(obj).
Reading error messages
A red error line contains three useful things: the error type and message, the file name and line number, and a stack trace. Click the file link, and DevTools opens the exact line. Read the first error first, because later ones are often a result of it.
The messages you will see most:
| Message | Usual cause |
|---|---|
Cannot read properties of undefined (reading 'x') | You used .x on something that is undefined. Find out why it is empty |
x is not defined | A typo, or the variable is outside the current scope |
x is not a function | You called something that is not a function, or a method name is misspelled |
Unexpected token | A syntax mistake such as a missing bracket or comma |
Breakpoints
A breakpoint pauses your code at a line so that you can look around. In the Sources tab, open your file and click a line number. Reload or trigger the code, and it stops there.
When paused, you can:
- See the values of all variables in scope, in the Scope panel on the right.
- Hover over any variable in the code to see its value.
- Type expressions into the Console, which now runs in that paused context.
- Step with the buttons: Step over runs the current line, Step into goes inside a function call, Step out finishes the current function, and Resume carries on.
- Check the Call Stack to see how you reached this line.
You can also write debugger; in your code. When DevTools is open, execution pauses there:
function calculateTotal(items) {
let total = 0;
for (const item of items) {
debugger; // pauses on each round
total += item.price * item.qty;
}
return total;
}
Remember to remove it before you publish.
Two more tricks. A conditional breakpoint (right-click the line number, Add conditional breakpoint) only pauses when an expression is true, such as item.id === 42. That saves you from stepping through 1000 loop rounds. Event listener breakpoints pause when a certain event, such as a click, fires.
A debugging routine that works
This is the order I follow, and it saves a lot of time:
- Reproduce it. Find the exact steps that cause the bug.
- Read the error. The message and the line number usually point at the place.
- Narrow it down. Put a breakpoint where the wrong value could first appear.
- Check your assumptions. Look at actual values. Is the variable what you believe it is?
- Change one thing at a time. If you change three things, you will not know which fixed it.
- Write down the cause. If you cannot explain it, you may have hidden it and not fixed it.
The Network panel
For anything that uses fetch, open the Network tab. Every request is listed with its status, size and time. Click one to see:
- The request URL and method.
- The request headers and payload that you sent.
- The response body, as the server returned it.
- The timing breakdown.
Many "my code is broken" problems are really "the server returned a 404 or an HTML error page". The Network tab shows you that in a few seconds. Filter by Fetch/XHR to hide images and scripts. The status column shows red for failures, and CORS problems appear there too.
Elements, Application and Performance
- Elements shows the live DOM and CSS. You can edit text and styles on the page and see the effect at once. Right-click an element and choose Break on, then Attribute modifications, to pause when JavaScript changes it.
- Application shows
localStorage, cookies and caches. You can edit or delete values by hand. - Performance records what the page does over a few seconds. Long yellow blocks are JavaScript tasks that block the thread. Start with the Main track and look for tasks flagged as long.
Source maps and minified code
If your code goes through a build tool, the browser runs the generated file. A source map links it back to your original files, so you can set breakpoints in the code you wrote. Most tools produce one in development mode.
Common mistakes
- Reading the last error and not the first. Fix the first one.
- Debugging a different file from the one running. Check the path in the Sources tab. Hard-reload with
Ctrl+Shift+Rto avoid cached scripts. - **Leaving
debuggeror noisy logs in production.** - Trusting a logged object. It shows the latest values, not the ones at logging time.
- Changing many things at once.
Try it yourself
- Take the
calculateTotalfunction above, give it an array of items and use a breakpoint to step through it. Watchtotalchange. - Use
console.tableon an array of three objects. - Open the Network tab and load any page. Find the largest file and the slowest request.
- Make a deliberate mistake, like calling
users.lenght, and use the error to find it.
const users = [
{ name: "Ali", age: 25 },
{ name: "Sara", age: 31 },
];
console.log("Plain message", users.length);
console.warn("Something looks off");
console.error("Something failed");
console.table(users); // nice table for arrays of objects
console.group("Details");
console.log("Inside the group");
console.groupEnd();
console.time("loop");
for (let i = 0; i < 1e6; i++) {}
console.timeEnd("loop"); // prints elapsed time
console.assert(users.length === 3, "Expected three users");
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account