JS Debugging
Debugging
Debugging is the process of finding and fixing problems in your code. The fastest way to debug JavaScript is using the browser Developer Tools (DevTools).
Open DevTools: F12 or Ctrl + Shift + I (Windows) / Cmd + Option + I (Mac).
Debug Console
The Console is your best friend when debugging. Use console methods to inspect values and understand program flow.
console.log("Hello");
console.warn("This is a warning");
console.error("This is an error");
Log structured data clearly:
const users = [
{ id: 1, name: "Ali" },
{ id: 2, name: "Veli" }
];
console.table(users);
Measure performance quickly:
console.time("loop");
let sum = 0;
for (let i = 0; i < 100000; i++) sum += i;
console.timeEnd("loop");
Debug Breakpoints
Breakpoints pause execution so you can inspect variables step by step.
- Open DevTools → Sources
- Click the line number to add a breakpoint
- Refresh or trigger the code
You can also add a breakpoint directly in code using debugger.
function calcTotal(price, tax) {
debugger; // execution pauses here (if DevTools is open)
return price + tax;
}
calcTotal(100, 20);
Useful controls while paused:
- Step over: run next line
- Step into: go inside a function call
- Step out: finish current function and return
- Resume: continue running until next breakpoint
Debug Errors
When an error happens, the Console shows the error type and the stack trace (where it happened).
function run() {
return notDefined + 1;
}
run();
Common debugging approach:
- Read the error message carefully (TypeError, ReferenceError, etc.)
- Click the file/line link in the Console
- Inspect the stack trace to find the root cause
Handle risky operations with try/catch (useful for JSON parsing):
try {
const data = JSON.parse("{ bad json }");
console.log(data);
} catch (e) {
console.error("JSON parse failed:", e.message);
}
Debug Async
Async code (Promises, async/await, timers, fetch) can be harder to debug because execution happens later.
Debug a Promise chain:
fetch("/api/data")
.then(res => res.json())
.then(data => {
console.log(data);
})
.catch(err => {
console.error(err);
});
Debug with async/await (often easier to read):
async function loadData() {
try {
const res = await fetch("/api/data");
const data = await res.json();
console.log(data);
} catch (e) {
console.error("Request failed:", e);
}
}
loadData();
Modern tip: Use the Network tab in DevTools to inspect requests, responses, status codes, and timing.
Source Maps (Quick Note)
If you use minified or bundled code in production, source maps help DevTools map the running code back to your original source files.
Next Step
Continue with JS Conventions to learn clean coding style and best practices.