Home » Javascript8 January 2010

print_r in Javascript

It’s a real headache when you have to work on objects and arrays in Javascript. It would be lot easier to detect elements of the Javascript objects/arrays if we have print_r function in Javascript like we have in PHP.

I googled the web and have found a very efficient print_r Javascript function. Here is the code:-


Source: http://brandnewbox.co.uk/articles/details/a_print_r_equivalent_for_javascript


Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed
  • very cool & good code, thank you very much for sharing.

    Can you contribute this code on my JavaScript library?

    Awaiting your response. Thank

  • The source of this js code is from another site. I mentioned the link in the post. So, you can post to your js bank yourself.

  • Khalid Chauhdry

    Thanks Mukesh Chapagain it’s a good function

  • Mukesh,

    I found when I setup your function if did not correctly place the UL elements around sub arrays in a multidimensional array.  

    So instead (used a bit of jquery to append write the output, but could just as easily be inner) I chose to add an extra function variable of return_value that will make the response be returned rather than echoed.  this way I was able to build the entire list before outputting…. 

    function print_r(theObj, return_value){
     var html = “”;
           if(theObj.constructor == Array || theObj.constructor == Object){
              for(var p in theObj){
                 if(theObj[p].constructor == Array || theObj[p].constructor == Object){
                 html += “[“+p+”] => “+typeof(theObj);
                 html +=  print_r(theObj[p], true);
                 html += “”;                
                 } else {
                  html += “[“+p+”] => “+theObj[p]+””;
           html += “”;
           if(return_value ==  undefined){
          return html;