Tutorials JavaScript Debugging Techniques
Ch 68 / 78
Chapter 68 Intermediate 8 min read JavaScript

JavaScript Debugging Techniques

Every developer spends a large chunk of their time debugging. Master the browser's DevTools, console methods, breakpoints, the call stack, and systematic bug-hunting strategies to fix bugs faster and write more resilient code.

What you'll learn
Types of JavaScript errors
All console methods beyond console.log
Using Chrome DevTools effectively
Breakpoints, watch expressions, call stack
The debugger statement
Systematic debugging workflows

Types of JavaScript Errors

Before you can fix a bug, you need to recognise what kind of error you are dealing with. JavaScript errors fall into a few broad categories:

SyntaxError
Syntax Error
Code cannot be parsed by the engine. Usually a missing bracket, quote, or comma. Caught before execution.
ReferenceError
Reference Error
Accessing a variable that has not been declared. Common when a variable is out of scope or mistyped.
TypeError
Type Error
Calling a non-function, accessing properties on null or undefined, or misusing an operator on the wrong type.
RangeError
Range Error
A value is outside the allowed range — for example, creating an array with a negative length or infinite recursion blowing the stack.
Logic Error
Logic Error
No runtime error is thrown, but the program produces the wrong output. The hardest category to spot because the engine cannot flag it.
Network Error
Network / Async Error
A failed fetch, promise rejection, or CORS issue. Appears as an unhandled rejection or a red entry in the Network panel.
JS — Common Error Examples
// SyntaxError — missing closing bracket
function greet(name) {
  console.log("Hello, " + name);
// ← SyntaxError: missing }

// ReferenceError — accessing undeclared variable
console.log(score); // ReferenceError: score is not defined

// TypeError — calling a non-function
const num = 42;
num(); // TypeError: num is not a function

// TypeError — null access
const user = null;
console.log(user.name); // TypeError: Cannot read properties of null

// Logic Error — wrong operator (= instead of ===)
let x = 5;
if (x = 10) { // assignment, not comparison — always true!
  console.log("x is 10");
}

Console Methods Beyond console.log

Most developers default to console.log, but the Console API has a rich set of methods that make debugging far more productive:

Method Use Case Visual in DevTools
console.log() General-purpose output for any value Plain text / expandable object
console.warn() Non-critical warnings Yellow background with ⚠ icon
console.error() Log an error with a stack trace Red background with ✕ icon
console.info() Informational messages (same as log in most browsers) ℹ icon prefix
console.table() Display arrays/objects as a formatted table Interactive sortable table
console.group() / groupEnd() Group related log messages under a collapsible heading Collapsible block
console.time() / timeEnd() Measure how long a code block takes to execute Prints elapsed milliseconds
console.count() Count how many times a line is reached label: N
console.assert() Log an error only if the condition is false Silent when true; error when false
console.trace() Print the current call stack at this point Stack trace listing
console.clear() Clear all previous console output Console wiped
console.dir() Show all properties of a DOM element or object Interactive property tree
JS — Console Methods in Action
// console.table — great for arrays of objects
const users = [
  { name: "Alice", role: "admin", age: 28 },
  { name: "Bob",   role: "user",  age: 35 },
];
console.table(users);

// console.group — structured logging
console.group("User Auth Flow");
  console.log("Checking credentials...");
  console.warn("Token expires in 5 min");
  console.error("Invalid password attempt");
console.groupEnd();

// console.time — measure performance
console.time("fetchUsers");
await fetch("/api/users");
console.timeEnd("fetchUsers"); // fetchUsers: 342ms

// console.assert — conditional error
const age = -1;
console.assert(age >= 0, "Age must be non-negative! Got:", age);

// console.trace — see who called this function
function processPayment() {
  console.trace("processPayment called from:");
}

Chrome DevTools — Your Debugging HQ

Chrome DevTools (and its equivalent in Firefox, Edge, and Safari) is the most powerful debugging tool available to a JavaScript developer. Open it with F12 or Ctrl+Shift+I (Mac: ⌘+⌥+I).

Console Panel
Run JS expressions interactively, view logged output, and catch runtime errors with full stack traces.
Sources Panel
Browse source files, set breakpoints, step through code line-by-line, and inspect the call stack and scope.
Network Panel
Inspect every HTTP request — headers, response body, timing, status codes, and CORS errors.
Performance Panel
Record and analyse CPU flame graphs to identify slow functions and rendering bottlenecks.
Application Panel
Inspect localStorage, sessionStorage, cookies, IndexedDB, and Service Workers in one place.
Elements Panel
Inspect and live-edit the DOM and CSS. Break on DOM mutations to catch which JS touched an element.
Pro Tip
In the Console, type $0 to reference the last selected DOM element, $_ to access the last evaluated expression, and $(selector) as a shorthand for document.querySelector().

Breakpoints — Pausing Code Execution

A breakpoint tells the browser to pause execution at a specific line so you can inspect variables, the call stack, and scope at that exact moment. There are several types:

Line-of-code
Click the line number in the Sources panel. Execution pauses every time that line is reached.
Conditional
Right-click a line number → "Add conditional breakpoint". Pauses only when your expression is true — ideal for loops.
Logpoint
Prints a message to the console without pausing — like console.log without touching your source code.
DOM mutation
Elements panel → right-click a node → "Break on" → subtree modifications, attribute changes, or node removal.
Event listener
Sources → Event Listener Breakpoints. Pause on any click, XHR, fetch, timer, or custom event anywhere on the page.
Exception
The "Pause on exceptions" button (⏸✕) in Sources pauses the moment any uncaught (or caught) exception is thrown.
JS — The debugger Statement
// The debugger statement acts as a programmatic breakpoint.
// DevTools must be open for it to pause execution.

function calculateTotal(items) {
  let total = 0;

  for (const item of items) {
    debugger; // ← DevTools pauses here on every iteration
    total += item.price * item.qty;
  }

  return total;
}

// Conditional debugging — only pause when something looks wrong
function processUser(user) {
  if (!user.email) {
    debugger; // pause only when email is missing
  }
  // ... rest of logic
}

// ⚠ Always remove debugger statements before committing to production!
⚡
Free Resource
Download our JavaScript Cheat Sheet
Syntax, built-in methods, ES6+ features — all on one page.
Get Sheet

Reading the Call Stack & Scope

When paused at a breakpoint, the DevTools Sources panel shows you three critical panes on the right side:

Call Stack
Shows every function call that led to the current pause point. Click any frame to jump to that function's context and inspect its local variables.
Scope
Lists all variables in the current scope — Local, Closure, Module, and Global. Shows their live values as you step through.
Watch
Add any JS expression (e.g. user.cart.length) and DevTools re-evaluates it at every pause — no logging needed.
JS — Reading a Stack Trace
/* Imagine this error in the console:
   TypeError: Cannot read properties of undefined (reading 'name')
     at renderUser    (app.js:42)
     at loadDashboard (app.js:18)
     at init          (app.js:5)

   Reading bottom-up:
   1. init() called loadDashboard()
   2. loadDashboard() called renderUser()
   3. renderUser() crashed on line 42 — user is undefined there.
   Fix: add a null-check before accessing user.name
*/

// Before fix — crashes if user is undefined
function renderUser(user) {
  document.getElementById("name").textContent = user.name;
}

// After fix — safe with optional chaining
function renderUser(user) {
  document.getElementById("name").textContent = user?.name ?? "Unknown";
}
Note
Stack traces are read bottom-up — the bottom frame is where execution started, the top frame is where the crash occurred. Your own code frames are in the middle; ignore the framework internals below.

Stepping Through Code

Once paused at a breakpoint, you control execution one step at a time using the Sources toolbar buttons. Knowing when to use each is key to efficient debugging:

Resume (F8)
Continue execution until the next breakpoint or end of script.
Step Over (F10)
Execute the current line, but do not enter any function calls. Stays at the same call stack depth.
Step Into (F11)
Enter the function call on the current line — go deeper into the call stack to trace the bug inside the function.
Step Out (Shift+F11)
Finish the current function and return to the caller — useful when you've entered too deep.
Step (F9)
Execute exactly one statement, entering functions when encountered.

Key DevTools shortcuts to memorise:

Open DevTools
F12 / Ctrl+Shift+I
Open Console directly
Ctrl+Shift+J
Open Go-to-file
Ctrl+P
Resume execution
F8
Step over
F10
Step into
F11
Step out
Shift+F11
Toggle breakpoint
Ctrl+B
Inspect element
Ctrl+Shift+C
Clear console
Ctrl+L
Advertisement

A Systematic Debugging Workflow

Random guessing wastes time. Apply this structured process every time you hit a bug:

1
Reproduce the bug consistently
Find the exact steps that trigger the problem. A bug you can't reproduce reliably is almost impossible to fix. Note the expected vs actual behaviour.
2
Read the error message carefully
The console error includes the error type, a message, the file name, and the line number. Read all of it — especially the stack trace.
3
Isolate the failing code
Use binary search debugging — comment out half the code and check if the bug persists. Keep narrowing down until you pinpoint the exact function or line.
4
Inspect state at the crash point
Set a breakpoint just before the error. Use the Scope pane and Watch expressions to check what values your variables actually hold vs what you expect.
5
Form a hypothesis and test it
Based on your inspection, form one theory about the root cause. Change exactly one thing to test it. Don't change multiple things at once.
6
Fix, verify, and prevent recurrence
After fixing, verify the original steps no longer reproduce the bug. Add a test (or at minimum a comment) explaining why the fix is needed, to prevent regression.

Common JavaScript Bugs & How to Fix Them

These patterns account for a huge proportion of real-world bugs:

JS — Common Bug Patterns
// ─── BUG 1: == vs === ─────────────────────────────────────────
// Problem: loose equality causes unexpected type coercion
if ("5" == 5)  { } // true  — coerces string to number (BAD)
if ("5" === 5) { } // false — different types (GOOD)

// ─── BUG 2: var hoisting ──────────────────────────────────────
console.log(x); // undefined (not ReferenceError!) — var is hoisted
var x = 10;
// Fix: use let / const — they are NOT hoisted this way

// ─── BUG 3: async not awaited ─────────────────────────────────
async function getUser() { return { name: "Alice" }; }
const user = getUser(); // Promise, not the user object!
console.log(user.name); // undefined — must await
const user2 = await getUser(); // ✓ correct

// ─── BUG 4: forEach doesn't break ────────────────────────────
[1,2,3].forEach(n => {
  if (n === 2) return; // only skips this iteration, not the loop!
});
// Fix: use for...of with break, or Array.find()

// ─── BUG 5: mutating array while iterating ────────────────────
const arr = [1,2,3,4];
arr.forEach((n, i) => {
  if (n % 2 === 0) arr.splice(i, 1); // indices shift — skips elements!
});
// Fix: filter instead
const odds = arr.filter(n => n % 2 !== 0);

// ─── BUG 6: closure inside a loop ────────────────────────────
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100); // prints 3,3,3 — all share same i
}
// Fix: use let (block-scoped per iteration)
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100); // prints 0,1,2 ✓
}
Common Mistake
Using console.log to debug async code can be misleading — the object logged is a reference that may have changed by the time you expand it. Use console.log(JSON.parse(JSON.stringify(obj))) or a breakpoint instead to capture a true snapshot.

Try It Yourself

Live Editor
✎ Editor
👁 Preview
Quick Check — Chapter 68

Which console method pauses execution in DevTools and shows a full stack trace?

Chapter Summary
  • JavaScript errors fall into six main types: SyntaxError, ReferenceError, TypeError, RangeError, Logic Errors, and Network Errors.
  • The Console API offers far more than console.log — use table, group, time, assert, and trace for targeted debugging.
  • Chrome DevTools Sources panel lets you set line, conditional, logpoint, DOM, and event listener breakpoints without touching source code.
  • The debugger statement is a programmatic breakpoint — always remove it before committing to production.
  • Always read stack traces bottom-up — your code is usually near the top; the root call is at the bottom.
  • Apply the 6-step debugging workflow: reproduce → read error → isolate → inspect state → hypothesis → fix and verify.
  • Know the top 6 bug patterns: == vs ===, hoisting, unawaited async, forEach limitations, mutating while iterating, and closure in loops.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel