JavaScript debugging function similar to PHP var_dump / print_r

There is no javascript debugging function as like PHP’s print_r / var_dump function. Here’s one i have found.

/**
* Function : var_dump()
* Arguments: The data - array,hash( associative array),object
* The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
* Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
*/
function var_dump( arr, level ) {
    var dumped_text = "";
    if ( ! level ) level = 0;

    var level_padding = "";
    for ( var j=0; j<level+1; j++ ) {
        level_padding += "    ";
    }

    if ( typeof(arr) == 'object' ) {
        for ( var item in arr ) {
            var value = arr[item];

            if ( typeof(value) == 'object' ) {
                dumped_text += level_padding+"'"+item+"'=> array(n";
                dumped_text += var_dump( value, level+1 );
                dumped_text += "n" + level_padding + ")n";
            } else {
                dumped_text += level_padding+"'"+item+"'=>""+value+""n";
            }
        }
    } else {
        dumped_text = "===>" + arr + "<===(" + typeof( arr ) + ")";
    }

    return dumped_text;
}

function test_var_dump( arr ) {
    document.getElementById('print_r').innerHTML = '<pre>' + var_dump(arr) + '</pre>';
}

The html div element having id print_r should be placed where you want to see the results. And the JS codes should be placed anywhere between this div and closing body tag but not before this division.

Now you can test array value with the test_var_dump function. Example:

/* Create some array element to test. */

var array_sub1 = new Array( "Hello World", 'Php test', 100, '200' );
var array_sub2 = new Array( "Facebook", 'Google' );
var array_sub3 = {
    'array_sub1': array_sub1,
    'array_sub2' : array_sub2
};
var array_parent = {
    'array_sub1': array_sub1,
    'array_sub2' : array_sub2,
    'array_sub3' : array_sub3
};

/* Test the function */
test_var_dump( array_parent );