Thursday, April 26, 2007

Tip: Make sure you declare JavaScript For loops correctly or Firefox go boom

So far this year at my day job I have been working on my first AJAX application. It's still ASP.NET on the server, and also happens to be my first .NET 2.0 app. To the user though, once you are on a page, there are no postbacks. First off, if you are developing AJAX applications, you just have to get Firebug, as they say web deveopment evolved indeed. Jay Atwood (who works for my old masters) has an excellent article at Coding Horror called Firefox as an IDE, and it pretty much echoes my sentiments exactly on Firebug. This app I am working on is a combination of ASP.NET AJAX controls, a third-party control I don't want to mention by name, and a good chunk of custom code.

So what do you do when Firebug in Firefox, you new favorite development tool, consumes 100% CPU utilization running your app and you have to crash it to get your machine back? I went through the stages of grief in about 30 seconds, and wrote off Firefox compatability with my application for a while. See I chalked it up to a problem with the 3rd party control I was using (itself AJAXed to the nines) until I had another client-side problem with the app in Internet Explorer and the thought of debugging this without Firebug seemed a fate worse than having to sit through Year of the Dog. So I dug into the code, which I hadn't written, and I saw JavaScript similar to this in the execution path that was causing Firefox to hang:

var startIndex=0;

for(i=startIndex; i < endIndex; i++) {
//Do some stuff here
}

This code works 100% in Internet Explorer 7, why is this causing Firefox to go crazy? Well once I figured out the execution path, I was able to breakpoint it in Firebug, because as I suspected Firefox is getting stuck in an infinite loop. What happens? i is reinitialized to startIndex after every run of the loop. You have to declare the loop like this for it to work fine:

var startIndex=0;

for(var i=startIndex; i < endIndex; i++) {
//Do some stuff here
}

Putting the var before i is the way it ought to be as far as I can tell, but both Internet Explorer and Firefox do the wrong thing by developers here. Both browsers should be sticklers about requiring var in a loop variable declaration and produce a clear JavaScript interpreter error before the code has the change to run. Once I found this issue, I searched through all the rest of the custom JavaScript code in the application and found that about half the JavaScript for loops were declared with var and the other half were not. Fixing all these loops resolved all the weirdness (but not out right infinite loops, odd) other developers and some testers were reporting using Firefox, imagine that!