Debugging: Beyond console.log
Debugging: Beyond console.log
I'll admit it—I'm guilty of using console.log to debug. I don't think it's a crime. I just want to see the value of a variable real quick while I'm on my warpath to squash a bug. I want to make sure it is what I think it is.
But today, let's talk about something better: the debugger statement.
What Even Is It?
The debugger statement invokes any available debugging functionality, like setting a breakpoint. If no debugger is available, it does nothing. No crash. No error. Just silence.
I think it's cool as hell.
How I Use It
VSCode has a nifty feature where you can literally type debugger right before the line you want to inspect. Like this:
function calculateTotal(items) {
const sum = items.reduce((a, b) => a + b, 0);
debugger; // 👈 Execution pauses here
return sum * 1.08; // tax
}
Once Chrome (or whatever browser) hits that line, everything stops. The world pauses. You can now:
- See every variable's current value
- Step through code line by line
- Inspect the call stack
- Modify values on the fly
- Continue when you're ready
Why It's Better Than console.log
| console.log | debugger |
|---|---|
| Clutters your code | One line, removable |
| Shows one moment in time | See the whole state |
| Need to refresh to see changes | Real-time inspection |
| Guess and check | Actually understand the flow |
| Forgot to remove it? Production bug. | Stops in dev, ignored in prod |
My Workflow Now
- Reproduce the bug - Know exactly when it happens
- Drop a debugger - Right before the suspicious code
- Refresh and trigger - Browser stops automatically
- Inspect everything - Variables, scope, call stack
- Step through - F10 to go line by line
- Find the issue - Usually a typo or wrong assumption
- Fix and remove debugger - Clean code, happy life
Pro Tips
💡 Conditional Debugging
Only want to break when userId === 5?
if (userId === 5) {
debugger;
}
⚠️ Don't Commit Debuggers
ESLint can catch these. Set up a pre-commit hook. Future you will thank present you.
The Bottom Line
console.log isn't evil. I still use it for quick checks. But when I'm actually stuck—when the bug is hiding and I'm chasing ghosts—the debugger statement is my weapon of choice.
It's like having X-ray vision into your code. And once you get used to it, going back to console.log feels like debugging with a blindfold on.
Next time you're stuck, try dropping a debugger. You might surprise yourself.
—Greg, recovering console.log addict