Debugging JavaScript and jQuery

It’s time to use the tools discussed in this chapter, especially Firebug (or the Chrome developer tools) and JSLint—they’ll catch many errors for you. Rather than using alert calls with variables and objects, place breakpoints and inspect the values of each object/variable as they are manipulated by your scripts. Also, make liberal use of the real-time editing.

Separating markup from functionality is the way of modern web development, for many reasons. One reason for keeping your JavaScript/jQuery code in an external .js file is that it helps the debugger correctly match the error with the actual line number, not to mention it keeps your code unobtrusive.

Make your projects test driven. Later in the book, I describe how to use QUnit to add unit tests to your projects. As you probably already know, although jQuery handles most cross-browser concerns, it’s still necessary to test in different browsers and environments, including portable devices like iPhones. Having a full test suite will make it easier to detect and squash cross-browser bugs.

For small bits of code, like one-liners, use console applications like jconsole and Rhino to make sure you’re getting the expected results.

Make sure of the obvious. The most experienced programmer may miss something obvious. Who hasn’t added a script tag for including jQuery, only to find out much later, to great dismay, that the path was mistyped? The debuggers will let you know quickly if the $ variable is undefined.

Being aware of browser-specific issues and their particular behaviors is important. That trailing comma in an object literal is just priceless after you’ve developed in a browser like Firefox or Safari for hours, only to have your beautifully scripted project explode in IE.

One point we mention time and again in this book is the necessity to really grok JavaScript. The learning curve for jQuery is low; it’s a wonderful framework for beginners to create dazzling JavaScript effects. However, advanced users doing full development shouldn’t treat it as a black box. It embraces and extends JavaScript, and thus requires JavaScript understanding.

Of course, there are all the other regular tips as well. For example, make sure your HTML and XML are well formed, use version control tools like Mercurial or Git, and call on the Google or Stack overflow gods when you’re really stuck.

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

Your email address will not be published. Required fields are marked *