1. Technology

JavaScript Alert

Basic Debugging using JavaScript itself


The JavaScript language itself provides very few debugging tools. One of the few that it does provide and perhaps the most useful is alert(). The alert command allows you to pop up a message in your browser.

So how do you use alert to help you debug your code?

Well there are two ways a JavaScript alert can be used. The first way is to set it up to display a static message. By placing several alerts in different spots in your code and having each display a different message you have a crude way of tracing the processing flow through your code. The alert messages will pop up one after the other allowing you to tell when each is run and providing you with information on the path that the processing if following through your code.

If you place an alert inside a function then you can tell when the function is called by seeing when the alert pops up. Place an alert inside a loop and you can tell how many times the processing goes around the loop.

function x(a) {
alert('start of function x');
for (var i = a.length; i >= 0; i--) {
alert('start of loop');

The other way to use alert is to get it to display the value contained in a variable. The alert message will pop up displaying the value contained in the variable that you selected at that point in the processing. That enables you to tell whether the variable contains the value that you expect it to contain at this point in the processing and helps you to determine if the code has gone wrong.

var z = x + y;
alert('z = '+z);

One thing to watch out for when placing alerts in your JavaScript particularly when you place them inside loops is that you actually have an exit condition in the code so that you will not be stuck in the loop displaying alerts forever. This is more important in those browsers where the alert dialog does not provide an option for disabling JavaScript on the current page (so as to end the processing once you have gathered enough data to tell what is going on).

Using Javascript alerts has become less important recently with most current browsers now providing a built in JavaScript debugging tool (the exception being Firefox where you need to install the debugging tool extension separately). These debugging tools not only make it really easy to trace the path that the processing follows through your code and check what values any field contain at any time, they allow you to do it without your needing to change your JavaScript code at all since they do not require that you add alert() statements. This avoids the problem that can sometimes occur where changing the code to add an alert makes the problem you are trying to find disappear.

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. Coding Tips
  6. JavaScript - Basic Code Debugging Tools

©2014 About.com. All rights reserved.