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.
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:
null or undefined,
or misusing an operator on the wrong type.// 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 |
// 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).
$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:
console.log without touching your source code.// 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!
Reading the Call Stack & Scope
When paused at a breakpoint, the DevTools Sources panel shows you three critical panes on the right side:
user.cart.length) and DevTools re-evaluates it at
every pause — no logging needed./* 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";
}
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:
Key DevTools shortcuts to memorise:
A Systematic Debugging Workflow
Random guessing wastes time. Apply this structured process every time you hit a bug:
Common JavaScript Bugs & How to Fix Them
These patterns account for a huge proportion of real-world bugs:
// ─── 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 ✓
}
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
Which console method pauses execution in DevTools and shows a full stack trace?
- 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— usetable,group,time,assert, andtracefor 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
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.