Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 43 of 58

Debugging with the browser tools

Find and fix JavaScript bugs with console methods, breakpoints, stepping and the debugger statement in your browser's developer tools, plus a calm method.

13 minClasses and errorsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonOpen the developer tools, read an error, pause code with a breakpoint, step through it and watch variables to find why a result is wrong.

After this lesson you can open your browser's developer tools, understand an error message, stop a program part-way and watch its variables change. These skills save more time than any amount of memorised syntax.

The menus here describe Chrome and other Chromium browsers such as Edge. Firefox and Safari have the same ideas under slightly different names.

Open the tools

Press F12, or Ctrl+Shift+I on Windows and Linux, or Cmd+Option+I on a Mac. Or right-click the page and choose Inspect. The panels you need most are:

  • Console: errors, warnings and anything you print. You can also type code here and press Enter to run it.
  • Sources: your files, with a place to set breakpoints.
  • Elements: the live DOM, handy once you reach The DOM.
  • Network: every request the page makes, useful for Fetching data with fetch.

Read the error first

Most bugs announce themselves. A red message such as Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') tells you the kind of error, what went wrong and, on the right, a file name and line number. Click it and the Sources panel opens at that line.

Read the sentence slowly. That example means the code asked for something that does not exist, then tried to use it. The cause is usually a line earlier or later than the one reported, for instance a wrong selector that returned null. See Errors, try and catch for the common error types.

A bug to chase

This function should return the average of a list, but it prints NaN. Can you see why before you read on?

html
<pre id="out"></pre>
<script>
  const out = document.getElementById("out");
  const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };

  function average(numbers) {
    let total = 0;
    for (let i = 0; i <= numbers.length; i++) {
      total += numbers[i];
    }
    return total / numbers.length;
  }

  log("average:", average([4, 6, 8]));
</script>
result
average: NaN

The loop condition uses <= instead of <. On the last pass i is 3, numbers[3] is undefined, and 18 + undefined is NaN, which then poisons the total. This is called an off-by-one error and is one of the most common bugs there is. Change <= to < in the editor and the result becomes average: 6.

Method 1: print what you need

The simplest tool is console.log. Add a line inside the loop, such as console.log(i, numbers[i], total), and you would see undefined appear on the final row. Some other console methods are worth knowing:

javascript
console.log("a", 1, { x: 1 });          // several values at once
console.table([{ name: "pen", price: 10 }, { name: "book", price: 250 }]);
console.error("something broke");        // red, with a stack trace in the browser
console.warn("careful");                 // yellow
console.group("loading");                // indent following logs
console.log("inner");
console.groupEnd();
console.assert(1 === 2, "assert failed"); // prints only if the condition is false

console.table draws an array of objects as a grid, which makes lists of data far easier to read. Label your logs, for example console.log("total:", total), so you can tell them apart. And log objects as separate arguments rather than gluing them into a string, because the console lets you expand them.

Printing is quick, but it has a weakness: you must guess where to look, edit the file and reload. Breakpoints remove that.

Method 2: breakpoints

A breakpoint pauses the program at a line so you can look around.

  1. Open Sources and click your file.
  2. Click the line number where you want to stop. A marker appears.
  3. Make the code run, for example by reloading the page.

The program freezes just before that line. Now look at the right-hand side:

  • Scope lists the variables that exist right here and their current values.
  • Watch lets you add any expression, such as total or numbers[i], and see it update.
  • Call stack shows which functions led here.

Then use the step buttons along the top:

  • Resume runs until the next breakpoint.
  • Step over runs the current line and stops on the next, treating a function call as one step.
  • Step into goes inside the function that the line calls.
  • Step out runs the rest of the current function and stops back in the caller.

Put a breakpoint on total += numbers[i]; and click Resume repeatedly. You will watch i go 0, 1, 2, 3 and see numbers[i] become undefined on the last round. The bug reveals itself.

You can also right-click a breakpoint to make it conditional, for example i === 3, so it pauses only when the condition is true. That is a big help in long loops.

Method 3: the debugger statement

Sometimes it is easier to write the pause into your code:

javascript
function average(numbers) {
  let total = 0;
  for (let i = 0; i <= numbers.length; i++) {
    debugger; // pauses here if the developer tools are open
    total += numbers[i];
  }
  return total / numbers.length;
}

With the tools closed, nothing happens, but remove it before publishing. Leftover debugger lines are a classic embarrassment.

A calm method

When something is wrong, resist the urge to change code randomly.

  1. Reproduce it. Find steps that make the bug happen every time.
  2. Shrink it. Remove code until the smallest program that still fails is left.
  3. Guess one cause, then test it with a log or breakpoint.
  4. Change one thing at a time, and re-run.
  5. Read your assumptions. The bug is usually where you were sure the code was fine.

Explaining the problem out loud, to a friend or even a rubber duck, often shows you the mistake before you finish the sentence.

Common mistakes

  • Ignoring the first error. Later errors are often side effects of the first. Fix the top one and reload.
  • Debugging a stale page. If your edit seems to have no effect, you may be looking at a cached file. Do a hard reload, or tick "Disable cache" in the Network panel while the tools are open.
  • Changing several things at once. Then you cannot tell which change helped.
  • Trusting a log without labels. Always print a name with the value.
  • Leaving console.log and debugger in finished code. Clean them up.
  • Not looking at the real value. Logging typeof or the value itself often shows a string where you expected a number. See Type conversion and equality.

Exercise

Paste the buggy average function into the HTML viewer inside a <script> tag, with a console.log of the result, and open the browser console. Add a console.log(i, numbers[i], total) line inside the loop and find the bad row. Then open the same page, set a breakpoint on the total += line, and step through with Resume, watching i and total. Finally fix the bug and check that the answer is 6.

That finishes this section. Next, the course moves into the page itself, starting with The DOM.

Key points

  • The Console shows errors with the file and line number, so read the first line of the message and click the location.
  • console.log, console.table and console.error help you see values, but breakpoints let you stop time and look around.
  • Step over, step into and step out move through code one line at a time while Watch and Scope show the variables.
  • The debugger statement pauses execution at that line whenever the developer tools are open.
  • Debug by narrowing down: reproduce the bug, guess, test the guess, and change one thing at a time.

Check yourself

1. A function returns NaN. What is the best first step?
2. What does the debugger statement do?
3. You are paused on a line that calls another function. Which button runs that call and stops on its first line?
4. Where do you find the line number of an error?

Free tools for this lesson