Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 156 Β· Errors and Debugging

Debugging Techniques

Find bugs faster with browser DevTools breakpoints, the debugger statement, stepping, watch expressions and smarter console logging strategies.

Writing code is half the job. The other half is figuring out why it doesn't do what you expected. Debugging is a skill you can learn, just like syntax: a set of tools plus a calm, methodical way of using them.

You already know the first tool, console.log(), from The Console and First Debugging Steps. This lesson goes further. You'll pause running code with breakpoints and the debugger statement, step through it line by line, watch values change, and use the console in smarter ways. Most important of all, you'll learn a process for hunting bugs that works even when the tools don't make the answer obvious.

A process for finding bugs

Before touching any tool, slow down. Most debugging time is wasted by guessing and changing random lines. Instead:

  1. Reproduce it. Find exact steps that make the bug happen every time. A bug you can't trigger, you can't confirm you've fixed.
  2. Read the error. If there is an error message, read its type, message and line number. It often points straight at the problem (see Errors and try...catch).
  3. Form a guess. "I think total is a string, not a number, by the time it reaches line 12."
  4. Test the guess. Log the value or pause at that line. Did reality match your guess?
  5. Narrow it down. If you don't know where the bug lives, split the code in half: is the value already wrong halfway through? Then the bug is in the first half. Repeat until you find the exact line.
  6. Fix, then verify. Repeat the steps from point 1 to make sure the bug is gone, and that nothing else broke.

Here is a small bug to practice on. The function should average a list of test scores, but the result is clearly wrong:

JS Find the bug

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Guess first, then test: add console.log(typeof score, total) inside the loop. You'll see that total turns into the string "08090100" because += concatenates strings (Type Conversion explains why). The fix is to convert each score with Number(score).

Logging strategies that save time

console.log() is the most-used debugging tool in the world, and for good reason: it's fast and works everywhere. A few habits make it far more useful.

Label everything. A bare number in the console is a puzzle. Wrap values in an object with shorthand properties to get the names for free:

JavaScript
console.log(price, qty);          // 4.5 3      which is which?
console.log({ price, qty });      // {price: 4.5, qty: 3}

Pick the right console method. The console has specialized tools that make patterns easy to spot:

JS Console tools for debugging

Press Run (or Ctrl + Enter) to see the console output here.

No output.

  • console.table() shows arrays of objects as a grid.
  • console.group() / console.groupEnd() indent related logs.
  • console.count() tells you how many times a line ran, which is great for "is this called twice?" questions.
  • console.assert() prints only when a condition is false, so it stays quiet when things are fine.
  • console.time() / console.timeEnd() measure how long code takes.
  • console.trace() (in browser DevTools and Node.js) prints the chain of function calls that led to the current line, which answers "who called this?".

The live object trap. In browser DevTools, a logged object is shown collapsed. When you expand it later, you see its values at the time you click, not at the time it was logged. If the object changed in between, the console misleads you. To log a snapshot, log a copy: console.log(structuredClone(state)) or console.log(JSON.stringify(state)).

Clean up afterwards. Debug logs left in production code clutter the console and can leak data. Remove them when the bug is fixed, or use a linter rule that warns about stray console.log calls.

Breakpoints: pausing your code

Logging shows you what you thought to ask for. A breakpoint shows you everything. When the code reaches a breakpoint it freezes, and you can inspect every variable in scope, the call stack, and the page itself, then continue one line at a time.

To set one in a browser:

  1. Open DevTools (F12, or Ctrl+Shift+I; Cmd+Option+I on a Mac).
  2. Go to the Sources panel (called Debugger in Firefox).
  3. Open your script file and click a line number. A marker appears.
  4. Do whatever triggers that code: reload, click a button. Execution stops before that line runs.

While paused, the side panels show:

  • Scope: every local, closure and global variable with its current value. You can even edit values to test a theory.
  • Call stack: the chain of function calls that got you here. Click an entry to jump to that function and see its variables.
  • Watch: expressions you add yourself, such as cart.length or total > 100, re-evaluated at every pause.

Hovering over a variable in the code also shows its value. And the console works in the paused context, so you can type scores.map(Number) to try a fix before changing the file.

Stepping through code

Once paused, the toolbar buttons move execution forward in small, controlled steps:

Button Shortcut (Chrome) What it does
Resume F8 Run normally until the next breakpoint.
Step over F10 Run the current line, including any function it calls, and stop on the next line.
Step into F11 If the line calls a function, go inside it and stop on its first line.
Step out Shift+F11 Finish the current function and stop right after it returns.

Step over when you trust a function; step into when you suspect it. Step out when you've gone into a function and realize the problem isn't there.

Special breakpoints

Right-click a line number for more options:

  • Conditional breakpoint: pauses only when an expression is true, like item.price < 0. Perfect for a bug that happens on the 500th loop iteration.
  • Logpoint: logs a message without pausing and without editing your code. It's a console.log you can't forget to delete.

DevTools can also pause on exceptions (a toggle in the breakpoints pane), on DOM changes (right-click an element in the Elements panel β†’ Break on), and on event listeners such as every click.

The debugger statement

Sometimes it's easier to set a breakpoint from the code itself. The debugger statement does exactly that: if DevTools is open, execution pauses there as if you'd set a breakpoint. If DevTools is closed, the statement does nothing.

Open your browser's DevTools first, then run this example. The browser pauses inside the loop on each discount; use Step over and watch price change in the Scope panel:

JS Pause with debugger (open DevTools first)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The example runs inside a sandboxed frame, so in DevTools it appears as a separate, unnamed source; the pause still works the same way. Press Resume to let it finish.

Never ship debugger statements. Anyone who opens DevTools on your live site would have the page freeze on them. Linters flag debugger for this reason, and many build tools strip it out.

Debugging without a debugger

Some bugs are not in a single line but in an idea. These techniques help when stepping through code doesn't make the problem jump out:

Rubber duck debugging. Explain the code, line by line, out loud, to a colleague, a rubber duck, or an empty chair. Describing what each line should do often reveals the line that doesn't.

Make a minimal reproduction. Copy the failing code somewhere small, like the editors in this course, and delete everything that isn't needed to show the bug. Either the bug disappears (so it lives in something you removed) or you're left with a few lines where the cause is obvious.

Check your assumptions. Bugs hide behind "that part definitely works". Confirm the boring things: is the function actually called? Is the variable the type you think? Is the array empty?

JS Check your assumptions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The assertion catches the real cause: the string "false" is truthy, so Omar counts as active. The filter was never the problem; the data was.

Take a break. It's a clichΓ© because it works. After twenty minutes of staring, a short walk often brings the answer.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. What does the debugger statement do when DevTools is closed?

    debugger only acts like a breakpoint when developer tools are open; otherwise it is ignored.
  2. 2. You are paused on a line that calls calculateTax(order). You suspect calculateTax is wrong. Which button do you press?

    Step into enters the called function so you can watch it work line by line.
  3. 3. A bug only appears when item.price is negative, deep inside a loop over 10,000 items. What is the most efficient tool?

    A conditional breakpoint pauses only when the condition is true, right at the interesting moment.
  4. 4. You log an object, change it, then expand the logged entry in DevTools. What do you see?

    DevTools reads the object's properties when you expand it. Log a copy, such as structuredClone(obj), for a true snapshot.

Summary

  • Debug with a process: reproduce, read the error, guess, test, narrow down, fix and verify.
  • Label logged values with { name } objects, and use console.table, group, count, assert and time where they fit.
  • Logged objects are live in DevTools; log a copy to see a snapshot.
  • Breakpoints pause code so you can inspect scope, the call stack and watch expressions, then step over, into or out.
  • Conditional breakpoints and logpoints target exactly the moment you care about.
  • debugger pauses when DevTools is open; never ship it.
  • Minimal reproductions, rubber ducking and checking assumptions solve the bugs tools can't.

Next: Strict Mode β€” let JavaScript catch silent mistakes for you.