Tutorials / Modern JavaScript: Async, Modules and the Browser / Debugging with browser DevTools

Debugging with browser DevTools

15 min read javascript
Course contents (16 lessons)
  1. Modern syntax
  2. Destructuring, spread and rest
  3. ES modules: import and export
  4. Objects, this and errors
  5. Classes and prototypes
  6. Understanding this in JavaScript
  7. Error handling: try, catch and custom errors
  8. Asynchronous JavaScript
  9. The event loop: how JavaScript handles waiting
  10. From callbacks to promises to async/await
  11. Fetch and REST APIs
  12. Working in the browser
  13. Local storage and session storage
  14. Debugging with browser DevTools
  15. Performance basics: debounce and throttle
  16. Node.js essentials
  17. Node.js and npm basics
  18. Working with files in Node.js
  19. A tiny HTTP server with Node.js
  20. Testing and the final project
  21. Testing basics with the Node.js test runner
  22. 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:

MessageUsual 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 definedA typo, or the variable is outside the current scope
x is not a functionYou called something that is not a function, or a method name is misspelled
Unexpected tokenA 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:

  1. Reproduce it. Find the exact steps that cause the bug.
  2. Read the error. The message and the line number usually point at the place.
  3. Narrow it down. Put a breakpoint where the wrong value could first appear.
  4. Check your assumptions. Look at actual values. Is the variable what you believe it is?
  5. Change one thing at a time. If you change three things, you will not know which fixed it.
  6. 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+R to avoid cached scripts.
  • **Leaving debugger or 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

  1. Take the calculateTotal function above, give it an array of items and use a breakpoint to step through it. Watch total change.
  2. Use console.table on an array of three objects.
  3. Open the Network tab and load any page. Find the largest file and the slowest request.
  4. Make a deliberate mistake, like calling users.lenght, and use the error to find it.
javascript
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