How to use the JS debugger keyword to debug your code
Here is the example we are going to be working with:
The debugger keyword is on line 13 in red. The syntax is simple. Just use
The code above is a simple page that we will use to help demonstrate the debugger. When the page is loaded, it has a body with a paragraph inside that says “This is in the body.” And we have a function that will run when we click on those words, in turn, allowing us to “hit” the debugger and start playing with the code to observe what is happening. Here is what the page looks like when we start it:
Let's say we have an error in our code but don't know where it is exactly it is or what is happening. This is where debugger comes into play. You can interact with the debugger by using the developer tools in Chrome. You can open it by
cmd + click and select inspect on the page. Now we have this open we have to “hit” that function where we placed the debugger. We can do that by clicking on “this is in the body”. Now you should see this screen:
First, when we run our code, it will stop at the debugger. Then, when we click the continue button, it will run until it “hits” the breakpoint and pause. On the right hand side, there is a drop down menu called “Breakpoints.” In the menu, we can see all of our breakpoints we have placed.
Another useful thing you can utilize is the Watchlist(Watch) menu on the right side. In here, it will show all the variables that have been defined in order. But first, we have to add them. We can do that by clicking on the + sign and adding it like so:
Then we can use the step button and walkthrough the code and watch the variables change based on what line we are on.
Other browsers have slightly different developer tool interfaces but you can still use the debugger keyword just a bit diffrent.