Display JavaScript object value

As you probably already know, JavaScript can be difficult to debug. One thing that has helped us out many times is this function to show all the properties of an object. This function recursively takes properties that are objects themselves and shows their properties. To see how it works, put a function call of “dumpProps(document)” in the “onclick” event of a button and you’ll see everything about the document.

This function provides a couple of advantages for debugging. First, it allows you to verify what object you are working with during your script. It also allows you to verify the properties of that object (maybe you can’t remember the property name or don’t know how to spell it). It is also good if you are working with a heirarchy of properties. For example, if you think it might be document.body.referer for the property you want, but aren’t sure, you can show all the document properties, recursively, to find out which one it is. (it’s actually document.referer).

This code uses confirm prompts so you don’t have to go all the way through all the properties once you find the one you want. Clicking cancel will stop the processing. (Note that if you click cancel while the function has been recursing, it will stop that level of recursion and you can continue on or click cancel on the parent level).

Here is the function:

    <script type="text/javascript">
        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)) {
                // 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);

This code should be placed in the section of your page so it can be used anywhere you need it. Note that the “parent” variable is optional and not needed for the initial call to the function. It is only used during the recursion.