Wednesday, April 11, 2012

Debugging Javascript: Blackbird, JSLint & dumpProps

JavaScript can be difficult to debug despite the tooling we got - IDE, Firebug, etc.

A naive way of doing debugging in JavaScript is to use alert() function. Unfortunately, alert falls short in this respect. Enter Blackbird. Blackbird is sort of a JavaScript console that is better than using alert(). As their website says, "You might never use alert() again."

Blackbird is attractive and useful but not might fall short in some debug scenarios. All too often, I have had a need to dump the insides of a JavaScript object - its properties. Fortunately, plain JavaScript can do this. This script can be found at the site and it works nicely with Blackbird (with a few modifications).

function dumpProps(obj, parent) {  
   // Go through all the properties of the passed-in object   
   for (var i in obj) {  
    // if a parent (2nd parameter) was passed in, then use that to   
    // build the message. Message includes i (the object's property name)   
    // then the object's property value on a new line   
    if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }  
    // Display the message. If the user clicks "OK", then continue. If they   
    // click "CANCEL" then quit this level of recursion   
    if (!confirm(msg)) { return; }  
    // If this property (i) is an object, then recursively process the object   
    if (typeof obj[i] == "object") {   
      if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }  

When you get your script working as expected you might want to run it through JSLint. JSLint is a code analysis tool following the coding rules as discussed by Douglas Crockford's book, JavaScript: The good parts. Essentially, JSLint looks for problems in JavaScript program. It is a code quality tool.

I hope that these stuff makes debugging JavaScript a little more pleasant.