In a previous post I introduced some simple debugging techniques for Google Apps Scripts, mainly involving the logging or displaying of messages, with or without variable values embedded within them. This is useful for simple scripts, but for anything more complex you’ll be better off using the debugger built into the Script Editor.
Using the debugger, you can set break points in the code at places of your choice. When code execution lands on a break point, it halts; while time remains frozen, you can check how your code is operating, examine variable values, read log messages etcetera.
Let’s start with some example code, as shown below (the code doesn’t do anything useful, so don’t get a headache trying to figure out its function!):
A break point is a place in your code where you’d like its execution to temporarily stop while you check things out. It’s denoted by a big red dot next to the line number, and is set by clicking on the line number. Click again to remove the break point.
Here you can see a break point set on line 20.
Click on the ‘insect’ icon (see the cursor position in the above image) to start the debugger. You’ll see that the code runs until the break point is reached.
You can inspect the state of the code variables at each break. View the variable values in the bottom pane:
In the bottom pane you’ll also see buttons that allow you to step in, step over, or step out of the current code function:
Here’s what they do:
Step Over: Executes the current line, including any functions that are called, then moves to the next line.
Step Into: Moves to the next line, as with Step Over, unless the line calls a function; in that case, jumps to the first line of the function.
Step Out: Leaves the current function and returns to the place from which it was called.