Concept Explanation
Imagine you are watching a movie and you see a ghost. You want to pause the movie, walk up to the screen, and see if the ghost is real.
The debugger keyword is that "Pause" button. It stops the code at a specific line, opens the browser's developer tools, and lets you inspect every single variable in memory.
Syntax or Core Structure
function calculateTax(price) {
const taxRate = 0.15;
debugger; // The code stops EXACTLY here
const total = price * taxRate;
return total;
}
Chrome DevTools Controls
- F10 (Step Over): Move to the next line.
- F11 (Step Into): Go inside a function.
- F8 (Resume): Keep running until the next debugger/breakpoint.
Real World Example
The "NaN" Bug: Your shopping cart shows "Total: NaN". Instead of logging everything, you put a debugger on the calculate line. You pause, look at the price variable, and realize it's an object instead of a number. Fix found in 10 seconds!
Best Practices
- Never leave debugger in code: Always delete the keyword before you save. It will freeze the website for anyone who has DevTools open!
- Conditional Breakpoints: In Chrome, you can right-click a line number and say "Only stop if x > 10."
- Watch Expressions: Use the "Watch" tab in DevTools to keep an eye on a specific variable as you step through the code.
Practice Exercises
- The Pause Button: Write a function with 5 lines of logic. Put
debuggeron line 3, run the code, and practice "Stepping" through the remaining lines. - The Scope Checker: Pause a function inside a loop and check the "Scope" tab in DevTools to see how the loop variable
ichanges. - The Call Stack: Research the "Call Stack" tab in the debugger and explain how it helps you find where a bug started.