How to Use Debugger Statement in JavaScript for Easy Debugging
Use the
debugger statement in JavaScript to pause code execution at a specific line when developer tools are open. This lets you inspect variables and step through code interactively.Syntax
The debugger statement is a simple keyword that you place in your JavaScript code where you want to pause execution.
When the browser's developer tools are open, the code will stop at this point, allowing you to inspect variables and step through the code.
javascript
debugger;
Example
This example shows how to use debugger inside a function. When the code runs with developer tools open, it pauses at the debugger line so you can check the value of sum.
javascript
function add(a, b) { const sum = a + b; debugger; return sum; } console.log(add(3, 4));
Output
7
Common Pitfalls
- For
debuggerto work, developer tools must be open; otherwise, it is ignored. - Leaving
debuggerstatements in production code can pause users' browsers unexpectedly. - Using
debuggeroutside functions or loops may pause code too early or late.
javascript
/* Wrong: debugger without dev tools open does nothing */ function test() { debugger; console.log('Test'); } test(); /* Right: Use debugger during development with dev tools open */
Output
Test
Quick Reference
Remember these tips when using debugger:
- Place
debugger;where you want to pause. - Open browser developer tools before running code.
- Remove
debuggerstatements before deploying.
Key Takeaways
Use
debugger to pause JavaScript execution for inspection.Open developer tools to activate the
debugger statement.Avoid leaving
debugger in production code to prevent unwanted pauses.Place
debugger thoughtfully to inspect variables at the right moment.