logo

Debugging JavaScript in Your Applications

Introduction:

Of all the languages we use on a daily basis as Domino Developers JavaScript has to be the trickiest of them all to debug. It's not necessarily that it's any harder than the other languages to debug, it's just that Internet Explorer doesn't really help us out. For example. Take this typical error dialog:

Image

The error message tells us almost nothing. After a while you start to get to know what each one might mean, but for the novice this is all but meaningless. It does provide the line number that the error happened on but trying to find this actual line is not always as easy as you might think. The line number includes all lines of JavaScript that happen to be included, as well as blank lines and whatnot.

So what do we do at this point? I sometimes find myself adding alert() boxes at strategic points in the code. You can use these prompts to tell us the values of certain variables as the code progresses. Eventually, if you're lucky, you'll discover what was causing the problem. This is no way to work though. It wastes too much time! We need to find the error fast. This article aims to describe a way of doing so.


A Simple Example:

Most JavaScript errors turn out to be really simple mistakes. Most often they are typos. Sometimes things are a lot more obscure but I will keep it simple here.

Take the form below, used for adding two numbers, as an example. Just three fields and a button:

Image

Now look at the code I wrote for the onclick event of the button. All it has to do is add the values in the first two fields and place the sum in the third:

function addThemUp(frm){
var i1 = frm.Number1.value;
var i2 = frm.Number2.value;
var fld = frm.total;

fld.value = i1 + i2;
}

Can you see my error already? Most of you probably can. For those who can't, the most valuable lesson to learn about JavaScript is that it's case-sensitive and this is the cause of endless errors. In this example I have called my field "Total" and refered to is as "frm.total" in the code. This is the cause of my "undefined" error. JavaScript looks for an object called "total" on the form and can't find it. Hence this reference is "undefined".

You might think I've spoilt the fun of describing how we go about finding the error. Well, not really - it's never fun. This article isn't a lesson in the theory of debugging. It's an article to describe the practice of debugging. Knowing how to debug effectively is something you either have or you have to pick up over the years and is well beyond the scope of this article.

Debugging the JavaScript:

The first essential step in debugging your code is getting your hands on a debugger. Microsoft give it away for free and you can get it here. Download and install a copy of Script Debugger before you carry on. You can't do much without it.

With Script Debugger installed, relaunch the browser and press the button again, you will see the same error message but a different dialog box, as below:

Image

If you click Yes the Script Debugger window will open and take you to the line of code that is causing problems.

Image

No more guessing which line it is. You know the exact line where the error occurred.

Taking it one step further:

Now that we know where the error is we can delve deeper to see what actually caused it. To do this we want to halt the code before the error and do some investigation. This is a simple case of adding the "debugger" keyword to your code, just before the line causing the error, as in the following example:

Image

When Internet Explorer encounters this line it stops executing the script and launches the debugger. This is what has happened in the above screen-shot.

Note: Browsers other than Internet Explorer will simply ignore this debugger keyword. You shouldn't worry too much about using it anyhow as it's most likely that you will only ever use it in development phase.


So, what do we do now we've paused it? Well, we need to find out exactly what it is that's undefined. To do this we can use the Command Window. From this little window you can easily check and re-assign values (at "run-time") to any of the variables that have been defined. Launch it from the View menu of the debugger or by clicking the button on the very right-hand-side of the toolbar.

To use the Command Window to check a variable's value you simply type in its name and press enter. In the shot below you can see that, one by one I've typed in the names of the variables in my function to test their values. The command window will return the value it associates with that variable on the line below. For i1 and i2 in this example you can see it contains the strings "12" and "56" but it tells us the variable called "fld" is undefined! Here lies our problem:

Command Window

Let's allow the code continue running and we can think this over. To do this you can either close the debugger or press F5. You will still see the error though! This is because fld is still undefined.

At this point you may well have that eureka moment and see the problem straight-away. If that's the case then you simply correct the code and pretend it never happened. Otherwise, we need to take this approach one step further. You can also re-assign variables from the Command Window. If you do this, then press F5 and see no errors, all is well. Once you've found the solution you can fix your code. Consider the lines in the Command Window in the screen-shot below:

Command Window

Using the typeof operator, I first check to see what it thinks the frm.total object is. As suspected, it's an undefined onject. On a hunch I try testing the typeof frm.Total, to see if I didn't give the field a capital initial. Eureka! frm.Total is an object and more than likely the field we are after. Now we can re-assign the "fld" object to point to the correct field. This is easy. All you do is type "fld = frm.Total" and press enter. Just like normal JavaScript! Test the result by testing the "typeof" of fld once more. This time it's an object. Allow the code to continue running and you shouldn't see an error. Instead you should see the total field populated with the correct value.

Trying it out for yourself:

Assuming you're using Internet Explorer and you have the the Script Debugger installed, you can test it for yourself using this form. Just click the calculate button:

This
Plus This
Equals



Summary:

Even if you already knew about and used the Microsoft Script Debugger I hope that you've found something new and useful from reading this article. It might not be the Holy Grail of script debugging but it's a basis to work on. Every situation is different and being able to debug each piece of code is something you will learn as you use it more and more.

You might be wondering how you debug script in other browsers, such as Mozilla. Well, that's a whole other ball game and probably the subject of a future accompanying article. Leave it with me.

Feedback

  1. JavaScript Errors

    Hi Jake, Thanks for the nice article. I do agree with you that Javascript is the most cumbersome language of all. It can sometime takes days to find a solution for certain problems. Cutting the long story short. I am struggling with a similar javascript error. I have tried debugging and found the cause of problem but for some reason couldn't find the solution. Please could you shed some light, it would be great help

    I have pasted the Javascript code below

    "function chgPM(src) {" + @NewLine + " var pm = src.options[src.selectedIndex].text;" + @NewLine + " var path = \'sys_wv?OpenForm&View=" + view + "&Sort=" + sort + "&Start=1&Count=" + CountNum + "&Query=\' + pm;" + @NewLine + " window.location.href = path; }"

    This lets users select a name from dropdown list and append the name to the url as a view search criteria and displays records with this name only. Which works fine with names which doesn't have ' in them. As soon as it encounters a name with apostrophe it startts failing and gives out weird error.

    Thanks in advance.

      • avatar
      • Jake
      • Tue 13 Jan 2004

      Re: JavaScript Errors

      Tony. Try the following line:

      "&Query=\' + escape(pm);" + @NewLine

      HTH Jake

      Show the rest of this thread

    1. How to check for undefined object in java script?

      Hi everyone,

      You guys are doing a wonderful job here. I have a problem to be addressed.

      My application is like this.

      html page divided as 3 frames..1st frame is loaded by a template file..2nd frame is loaded by calling a cgi inturn an exe....3rd frame is also loaded by calling a cgi and inturn an exe..

      The problem comes when i have a reference for an object in 2nd and 3rd frame in the 1st frame. i.e. when i assign a value for the 2nd frame object even when it's not created.

      So, it throws a script error..undefined or NULL...

      I would like to check for the existence of the object first, before assigning the value to it..

      Pls tell me how to check for the existence of an object say text box or whatever..

      Thanks Karthik

    • avatar
    • Jerry Carter
    • Tue 13 Jan 2004

    Script Debugger vs. Script Editor

    Jake,

    It's worth noting that if you already have Microsoft Script Editor installed, it will intercept errors just like Script Debugger - but it doesn't have a Command Window option under the View menu, or anywhere else I could see.

    I must have this on my system from when I installed Visual Studio. Not sure if it's downloadable. It does offer an object browser and project viewer, among other interesting tools I havn't bothered to get working...

    Jerry

    1. Re: Script Debugger vs. Script Editor

      jerry,

      select Debug - Windows - Immediate. this is Script Editor's command window.

      sean.

      Show the rest of this thread

    • avatar
    • David Frahm
    • Tue 13 Jan 2004

    Button element

    Nice job using a button element.

    Do you use those often in your "real" applications?

      • avatar
      • Jake
      • Tue 13 Jan 2004

      Re: Button element

      More and more nowadays. I normally reserve them for IE only intranets but buttons are now supported by later builds of Mozilla as well. Buttons are nice ;o)

    • avatar
    • Gustaf
    • Wed 14 Jan 2004

    Not in R5...?

    A collegue of mine noticed that Debugger isn't allowed to write in R5... Only on R6 (which I have).

      • avatar
      • Jake
      • Wed 14 Jan 2004

      Re: Not in R5...?

      You're probably right Gustaf. R5 only supports an old version of JavaScript. If you want to get round this and other issues when programming your code in Designer I suggest you disable JS in your Notes preferences. This will allow you to type any code you like in the JS pane! Jake

      Show the rest of this thread

  2. Something for everyone

    If I felt a bit alienated over the last few months with all the v6 stuff, this one floats my boat. I'm sure that this goes for anyone working in 5 or 6 who have tried to do a bit of js without even being allowed to go on a course in their job and who simply haven't got time to do all the php, mysql, puakma, python, linux, photoshop as well as javascript legwork.

    Another beauty which hits the spot!

  3. Mozilla JavaScript Debugger

    As a littel note for those who didn't notice yet: Mozilla has it's own JS Debugger called Venkman.

    Honestly speaking, I didn't make use of it that often yet, but it apears to be a lot more powerfull than Microsoft's JS debugger. At the price of beeing more confusing to the novice as well.

  4. Access to Java with Javascript

    I have also installed the ms debugger but I have to uninstall it. The reason: In an application we have integrated the following javascript-code to resize the notes viewapplet. function waitForViewApplet() { s_maxWaitSecs --; if ( s_maxWaitSecs<0 ) { window.clearInterval(s_waitVA); } else if ( document.applets.view.isActive() ) { var v = document.applets.view; window.clearInterval(s_waitVA); v.reshape (0, 0, v.offsetWidth, v.offsetHeight); } }

    When I activate the script debugger, I always get an errormsg for the line document.applets.view.isActiv()

    I think the reason for that is, that we access directly to the applet and at this point the script debugger can not handle this. So we get an error message. Another effect was that the view was not displayed after debugging ! Because this was critical I have uninstalled the debugger.

    If somebody fixed this let me know.

    Greetings from Germany

    Christian

  5. Debugging JavaScript

    You can also use opening the form using Mozilla Firebird instead of MS explorer.

    It has a Javascript Console in the menu that shows you detailed errors. Very nice, check it out

    http://www.mozilla.org

    1. Re: Debugging JavaScript

      I'm happy with this great tool <a href="http://www.scriptcode.com/vbscripteditor/">ExeScript PRO JavaScript Debugger</a>. Thanks for the nice article.

  6. JScript error handling

    JScript error handling.

    Table of JScript errors: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/j s56jslrfjscripterrorstoc.asp

    <html> <head> <script> <!-- function throwerror(){ try{ //Generate error a=b; }catch(e){ errorobj=e; errornr=(e.number & 0xFFFF); errordesc=e.description;

    //Display an alert alert(e+'\n'+errornr+'\n'+errordesc);

    /*Redirect to a form that uses Query_String to get the error number and then use that number as a key for DbLookUp to get the description from a document containing further information about the error. Then create an entry in your error handling database*/ window.location.href='$$ReturnGeneralError?OpenForm&errornr='+errornr; } } // --> </script> </head> <body text="#000000" bgcolor="#FFFFFF"> <button onclick="throwerror()">Throw Error</button> </body> </html>

    • avatar
    • IanO
    • Tue 27 Jan 2004

    debugger is not working as described

    re:If you click Yes the Script Debugger window will open and take you to the line of code that is causing problems.<br/> After first install, debugger opend but the window that should have contained the code was empty.<br/> So I check the (advanced>option labled "display a Notification about every script error" this got me to the "before installing the script debugger example" How do I get it to function as it did in the article?<br/> IE Version 6.0.2800 and the debugger docs say it is designed for IE4.<br/>Suggestions please.

    1. Re: debugger is not working as described

      After I have installed the debugger I recognized the same problem but I can fix it. If you have installed the Debugger and use him the first time, the debug window will be minimized. It than seams that the window is empty. Try to maximize the window. You have to resize the debug window (the one which contains the code) also. If you start the debugger the next time it should be okay.

    • avatar
    • Vec
    • Wed 28 Jan 2004

    might wonder

    Well I might sound stupid making such a post, heh that was just to say another great article :)

    ++ Tom

    • avatar
    • Mike
    • Fri 20 Feb 2004

    Intermittent problems, any others?

    I have used the debugger for several years and until recently have not been able to survive without it.

    After moving to XP Pro & the latest IE version (6.02) I get hung up about 50% of the time when stepping through lines of code.

    It's real hassle and requires shutting down the browser.

    Anyone faced with the same situation? Any suggestions?

    1. Re: Intermittent problems, any others?

      Hi Mike, yes I agree absolutely. I am using IE 6.02 and the script debugger and the combination can only be described as flaky. I have been searching for some time on the MSDN site for any troubleshooting guide for this but to no avail.

      Anyone out there found a solution to this...?

    • avatar
    • Jim Fricker
    • Tue 24 Feb 2004

    Alternative to debugger;

    An alternative to inserting "debugger;" into your code, to stop it before the error occurs, is to use the IE menu option View/Script Debugger/Open and use the script debugger (or Script Editor) to set a break point in the code using F9.

    If the code you wish to debug runs as soon as the page is loaded then open a browser window, use the menu option View/Script Debugger/Break at Next Statement and then navigate to the page you wish to debug either by using the next or back buttons or using a favorite or typing in the URL or using a simple (non javascript) hypertext link.

    Jim

    • avatar
    • Vlad
    • Fri 27 Feb 2004

    working with commad window hangs debugger

    Hello,

    I installed the debugger on my Windows 2000 Server, and when I open a command window and enter "Enter" key in it, the debugger hangs, so I have to end it with Task Manager. My NT works with the debugger just fine, but I really need it on 2000 because of NT problems with unicode.

    I would appreciate any advice, thank you very much,

    Vlad

  7. Debugger not allowing to debug javascript code

    I have installed the MS Debugger, but it is not functioning properly. I am not able to debug javascript. I can only debug the ASP code which I can do with Visual Studio as well.

    CAN ANYBODY HELP ME DEBUG JAVASCRIPT CODE, PLEASE!!!!!

  8. runtime errors

    Thank you so much! I was so clueless,now I think I've gotten it!

    1. Re: runtime errors

      Thank you very much for such a nice article. But here you covered topic when the error is comming program stops execution. How should I debug in situations when my code is doing wrong calcuations without stoping execution.

      Regards Hari.

  9. Runtime error

    Hi Just i want to solve the problem of Runtime errors, Debug errors and Javascript errors.

    Thanks with regards.

    • avatar
    • Char
    • Wed 23 Aug 2006

    runtime error

    I can't get through any site without a runtime error --- how do I stop this

  10. it is so usefull

    this is really usefull

    • avatar
    • binoy
    • Thu 12 Apr 2007

    very good article

    Thanks a lot. It is very exhaustive for a beginner.

      • avatar
      • hari
      • Fri 16 May 2008

      Re: very good article

      This article helped me a lot.Thanks .

  11. good

    I found my error. thanks for the help.

    1. Try Firebug!

      Javascript debugging in IE is no fun (even with the above tips), try Firefox + Firebug instead (www.getfirefox.com and www.getfirebug.com).

    • avatar
    • PCJIM
    • Thu 24 Jul 2008

    Thank you

    Your article is very good, thank you!

    • avatar
    • Rohit
    • Wed 15 Oct 2008

    Thank you, a very nice article

    I had been pulling my hair due to a javascript issue which appears in IE6 and doesn't appear in FF!! This article told me exactly what to do...

    Thankssss!!!

    • avatar
    • Amit
    • Tue 30 Dec 2008

    Java Script Debugging

    Very Nice Article. Thankx

  12. Feedback

    Good one

    • avatar
    • svend
    • Fri 29 May 2009

    great job!

    Thanks for this excellent article!

  13. Debugger not working

    hi

    debugger is not working. how to solve this ?

    • avatar
    • Sel
    • Mon 30 Nov 2009

    OMG, love microsoft: I've got of copurse original windows xp, all actualization downloaded and when i'm trying to run Ms Script Debugger it crashes IE and itself. Congratulations MS.

Your Comments

Name:
E-mail:
(optional)
Website:
(optional)
Comment:



Navigate other articles in the category "JavaScript"

« Previous Article Next Article »
Opening database relative URLs in JavaScript   Binding events to objects

About This Article

Author: Jake Howlett
Category: JavaScript
Hat Tip: Stephen Neal
Keywords: Debug; debugger; breakpoint; typeof; undefined;

Options

Feedback
Print Friendly

Let's Get Social


About This Website

CodeStore is all about web development. Concentrating on Lotus Domino, ASP.NET, Flex, SharePoint and all things internet.

Your host is Jake Howlett who runs his own web development company called Rockall Design and is always on the lookout for new and interesting work to do.

You can find me on Twitter and on Linked In.

Read more about this site »