Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q22 How do you debug JavaScript?

You are here: irt.org | FAQ | JavaScript | Misc | Q22 [ previous next ]

Placing stategic copies of alert() within code can inform you where in a script you get, e.g. if you place alert("#1") prior to some code, and then alert("#2") after, then if you never receive the #2 alert message then the problem lies between the two alert() lines.

Move one or other of the above alert() lines nearer to one another, until all that remains is one statement.  This will then identify the exact failing line.

When using object hierarchy, e.g. document.frame.form.element, if you don't get the results you expect, add an extra alert() function before the problem area, e.g. alert(document) or alert(document.frame) or alert(document.frame.form), this should give you some indication of whether the named object is right for your purposes.

When using JavaScript to dynamically produced HTML, e.g.

document.write("<p><b><i>bold italics</i></b>")

if the results are not as expected, then replace with:

document.write("&lt;p&gt;&lt;b&gt;&lt;i&gt;bold italics&lt/i&gt;&lt;/b&gt;")

or:

document.write("<xmp><p><b><i>bold italics</i></b></xmp>")

Although it looks more complicated, it at least gives you the chance to see exactly what is being generated by the browser.

To find a bug in a complex calculation using numbers or strings, break down the combination, e.g. the following code:

var date = new Date(string1.substring(0,4),string2.substring(4,6)-1,string3.substring(6,8));

Break it up as follows:

var a = string1.substring(0,4);
alert(a);
var b = string2.substring(4,6)-1;
alert(b);
var c = string3.substring(6,8);
alert(c);
var date = new Date(a,b,c);

This gives the ability to check that there are no data or logic errors.

There are also two script debuggers available:

Netscape JavaScript Debugger
http://developer.netscape.com/software/jsdebug.html

Microsoft - Script Debugger for Internet Explorer
http://www.microsoft.com/workshop/prog/scriptie/

The online utility Code Colorizer allows you to paste your code into a form and then will color your code so that you can see its structure. Useful if your text editor does not provide a similar function.

©2018 Martin Webb