Script Debugging

Script Debugging

Every now and again, you may hit a problem that is either difficult or inefficient to solve using logging to the console in isolation. For a long time, the console method was the best that JavaScript developers could hope for, but more recently both Firebug and the Chrome developer tools have provided interactive debugging features. This enables the creation of breakpoints, watches, and other goodies that are usually reserved for IDEs and compiled code. Figure A-3 shows the script debugger, and, while we won’t go into an in-depth tutorial on its use here, we will just explain the basic concept of a breakpoint.

APPENDIX: Debugging Android Web Apps

A breakpoint functions just like the Pause button on your DVD player. It stops the code from running at whatever point you set it. You can set a breakpoint anywhere you want—just click the line number label, and the code will pause when it reaches the line. Why is it useful to pause code execution? Well, at the moment you enter a breakpoint, you get an instant picture of the state of your script, including all the variables’ states. This is very useful, for example, to see whether a variable has been set yet or is still null. You can even change the value of a variable at runtime. You can also check the call stack , which shows the hierarchy of function calls; this can be very handy when you’re working with complicated flows and you want to know exactly who is calling whom. For example, if you set a breakpoint inside the function retrieveTaskDetails() which was called by the function getNewestTask(),you will be able to see this arborescence in the debug tool.

After inspecting your script, you have different options: step over, step in, and stop. Stepping over is just like hitting the Play button on your DVD player after a video has been paused—your script will continue to run until it reaches the end or another breakpoint. Stepping in can be used if your breakpoint is on a code line that calls another function. You can step into this function, and the script will freeze at the first statement of this function. Of course, you can stop running the script at any time by clicking the Stop button.

Figure A-3. The script debugger provides breakpoints and variable watches for more trying times.

APPENDIX: Debugging Android Web Apps

NOTE: You’ll often hear the statement “Smart developers don’t use the debugger.” The idea behind this is that, if you put your console log statements in the right places and trace the right info, it won’t be necessary to use the debugger, and you’ll be spared a lot of time (checking your console output is quicker than stepping into your code). The fact is, however, that you won’t always be testing your own code, and you’ll sometimes have to test code that you wrote a long time ago and don’t remember the details of—in these cases, the debugger offers some flexibility for seeing exactly what’s happening.