On this page
Debugging JavaScript
Effective debugging separates productive developers from frustrated ones. Master these tools early.
Browser DevTools
Open with F12, Ctrl+Shift+I (Windows/Linux), or Cmd+Option+I (Mac).
Console Techniques
console.log('Basic message');
console.error('Error message');
console.warn('Warning');
console.table([{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }]);
console.group('User Data');
console.log('Name:', user.name);
console.log('Email:', user.email);
console.groupEnd();
console.time('fetch');
await fetch('/api/data');
console.timeEnd('fetch'); // fetch: 234ms
console.trace(); // Print call stack
Breakpoints
- Open Sources tab
- Find your file
- Click line number to set breakpoint
- Trigger the code — execution pauses
- Inspect variables in Scope panel
- Step through with controls:
- Resume (F8)
- Step over (F10) — next line
- Step into (F11) — enter function
- Step out (Shift+F11) — exit function
Conditional Breakpoints
Right-click line number → Add conditional breakpoint:
user.id === 42
items.length > 100
debugger Statement
function processOrder(order) {
if (order.total > 1000) {
debugger; // Pauses here when DevTools open
}
// ...
}
Network Tab
Debug API calls:
- Filter by Fetch/XHR
- Inspect request headers, body, response
- Check status codes and timing
- Right-click → Copy as fetch to reproduce
VS Code Debugger
.vscode/launch.json for Node.js:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch App",
"program": "${workspaceFolder}/src/index.js",
"skipFiles": ["<node_internals>/**"]
},
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome",
"url": "http://localhost:5173",
"webRoot": "${workspaceFolder}/src"
}
]
}
Set breakpoints in VS Code gutter, press F5 to start debugging.
Common Bug Patterns
Undefined variable
console.log(userName); // ReferenceError
// Fix: check spelling, scope, initialization
Async timing issues
// Bug: logs before fetch completes
let data;
fetch('/api').then(r => r.json()).then(d => data = d);
console.log(data); // undefined
// Fix: use async/await
const data = await fetch('/api').then(r => r.json());
console.log(data);
Mutation bugs
// Bug: mutating state directly in React
state.items.push(newItem);
// Fix: create new array
setState({ items: [...state.items, newItem] });
Error Messages Decoded
| Error | Meaning |
|---|---|
ReferenceError: x is not defined |
Variable doesn’t exist in scope |
TypeError: Cannot read property 'x' of undefined |
Accessing property on null/undefined |
SyntaxError: Unexpected token |
Invalid JavaScript syntax |
RangeError: Maximum call stack |
Infinite recursion |
Read the full stack trace — the top line is where the error occurred; lines below show the call chain.
Debug systematically: reproduce → isolate → inspect → fix → verify.