One of the most popular ways of debugging in JavaScript when you are just getting started is to use the JavaScript alert() and input() functions. However there are times when clicking OK repeatedly can become tedious not to mention time consuming. Here are a few additional advanced JavaScript debugging techniques you can use to help increase your productivity.

JavaScript Console API Functions

Unlike the alert(), this the console API functions just displays a message in the debugger console and continue execution. For example:

console.log("Total is now: " + t);

There are other useful console API functions for debugging:

  • console.group()
  • console.info()
  • console.log()
  • console.groupEnd()

Breakpoints in JavaScript Debugger

You can pause execution of your JavaScript by adding a breakpoint in your web browsers Developer Tools (press F12). What's really cool about this technique is that it even works for things like AJAX and jQuery events.

This is done by simply clicking on the line number where you want your JavaScript to pause. You can even set multiple breakpoints. Then just reload your page and the script will stop wherever you told it to. In IE, you will need to also click the "Start debugging" button on the Script tab to enable the debugger.

Once your script has paused, you might notice that your browser is still waiting to finish loading the page.

While paused, you can view the value of variables in the right pane or by simply hovering your mouse over a variable in your source code. You can also continue execution of the script one line at a time. There are several buttons to do this including:

  • Step Into -- If the line of code contains a function, the debugger will go into the function and continue debugging line by line.
  • Step Over -- Regardless of whether the line contains a function, this button will continue to the next line of code.
  • Step Out  -- If you are in a function, it will continue execution of the rest of the function and pause on the next line as soon as it comes out of it.
  • Continue -- Will simply continue execution until the code ends or until the next break point.

Sometimes you may only want to start the debugger under a specific condition. For example, you might be looping through code 300 times but only want to start the debugger on loop number 258. In this case, you could use the debugger command. Example:

If (total == 258) {
debugger;
}

Have some useful JavaScript debugging techniques? I'd love to hear from you. Please share by adding them below.