console.log is great, but sometimes you want superpowers. What if you could freeze time in the middle of your program, look at every variable, and then move forward one line at a time, watching everything change?
You can! It's called the debugger, and it's built into every browser's DevTools.
Step 1: Add a breakpoint
A breakpoint is a spot where you want the program to pause. The easiest way to add one is to write the word debugger in your code:
function cartTotal(prices) {
let total = 0;
for (let i = 1; i < prices.length; i++) {
debugger; // ⏸️ pause here!
total += prices[i];
}
return total;
}
console.log(cartTotal([10, 20, 30]));
Step 2: Open DevTools and run your code
Open your web page, open DevTools (it must be open, or the debugger statement is ignored), and refresh the page. The program will freeze on the debugger line, and DevTools will switch to the Sources panel (called Debugger in Firefox), with that line highlighted.
Step 3: Look around
While paused, you can:
- Hover over any variable in your code to see its current value.
- Look at the Scope section in the side panel to see all the variables that exist right now, and their values.
- Type any expression into the Console to check things, like
prices[i] * 2ortypeof total.
Step 4: Step through the code
At the top of the debugger panel there are buttons for controlling time:
| Button | What it does |
|---|---|
| ▶️ Resume | Keep running until the next breakpoint |
| ⤵️ Step over | Run the current line and pause on the next one |
| ⬇️ Step into | If the current line calls a function, jump inside it |
| ⬆️ Step out | Finish the current function and pause back where it was called |
Click Step over a few times and watch i and total change in the Scope panel. You'll spot the off-by-one bug instantly.
Instead of typing debugger, you can also open your file in the Sources panel and click on a line number. A blue marker appears: that's a breakpoint. Click it again to remove it. No code changes needed!
The debugger can feel like a lot at first. Start with console.log (it solves most problems), and try the debugger when you're stuck on something tricky. Once you're comfortable with it, you'll wonder how you ever lived without it.