Debugging with DevTools
Browser DevTools are your most powerful debugging tool. Learn breakpoints, stepping through code, watching variables, and the call stack to find and fix bugs efficiently without relying solely on console.log.
DevTools Debugging
- Sources panel — View and debug your JavaScript files
- Breakpoints — Click line number to pause execution at that line
- debugger; — Keyword in code that acts as a breakpoint: if (bug) debugger;
- Step Over (F10) — Execute current line, move to next
- Step Into (F11) — Enter the function being called
- Step Out (Shift+F11) — Exit current function, return to caller
- Watch — Monitor specific variables/expressions as you step through code
- Call Stack — See the chain of function calls that led to current point
DevTools Code
// Using debugger keyword
function calculateDiscount(price, discount) {
// debugger; // Uncomment to pause here in DevTools!
const discountAmount = price * (discount / 100);
const finalPrice = price - discountAmount;
return finalPrice;
}
const result = calculateDiscount(100, 20);
console.log("Final price:", result); // 80
// Debugging a bug
function findBug(items) {
let total = 0;
for (let i = 0; i <= items.length; i++) { // Bug: <= should be <
// debugger; // Set breakpoint to see i and items[i]
total += items[i]; // items[items.length] is undefined!
}
return total;
}
// findBug([10, 20, 30]); // Returns NaN (bug!)
// DevTools workflow:
// 1. Open DevTools (F12)
// 2. Go to Sources panel
// 3. Find your file
// 4. Click line number to set breakpoint
// 5. Trigger the code (button click, page load)
// 6. Code pauses → inspect variables in Scope panel
// 7. Step through with F10/F11
// 8. Find the bug!
// Conditional breakpoint:
// Right-click line number → "Add conditional breakpoint"
// Only pauses when condition is true: i === 5
console.log("Pro tip: Use DevTools Sources panel instead of console.log for complex bugs!");Tip
Tip
Set breakpoints by clicking line numbers in DevTools Sources tab. Use conditional breakpoints (right-click line number) to pause only when a condition is true. This is faster than adding and removing console.log statements.
Use console.table for objects. console.time to profile. debugger; for breakpoints. Chrome DevTools > console.log.
Common Mistake
Warning
Leaving console.log and debugger statements in production code. They slow down the app and may expose sensitive data. Use a linter rule (no-console, no-debugger) to catch these before deployment.
Practice Task
Note
DevTools debugging: (1) Set a breakpoint in a function and step through it. (2) Use the Watch panel to monitor a variable's value. (3) Use the Call Stack panel to trace how you arrived at the current line.
Quick Quiz
Key Takeaways
- Browser DevTools are your most powerful debugging tool.
- Sources panel — View and debug your JavaScript files
- Breakpoints — Click line number to pause execution at that line
- debugger; — Keyword in code that acts as a breakpoint: if (bug) debugger;