var_dump() for Javascript

Every PHP dev who has already debugged a script must have used the var_dump() function. This function lets you see what values a variable or array has with them. Unfortunately such a function does not exist in Javascript :-( Here is an advanced one supporting:

  • String
  • Numbers
  • Function (the code is displayed)
  • Object
  • Boolean
  • Array
Example:
<script type="text/javascript">
  function hello_world(){alert("Hello World!");}
  foo = [];
  foo["yes"] = 1;
  foo["no"] = false;
  foo["alert"] = alert;
  foo["hello world"] = hello_world;
  var_dump(foo);

  function var_dump(obj, level) {
    var dump = "(<i>" + (typeof obj) + "</i>) : ";
    var level_nbsp = "";
    if(typeof level == "undefined"){var level = 1;}
    for(i = 0; i < 5*level; i++){level_nbsp += "&nbsp;";}
    switch(typeof obj){
      case "string":
        dump += obj + "<br/>\n";
        break;
      case "boolean":
        dump += (obj?"true":"false") + "<br/>\n";
        break;
      case "number":
      case "function":
        dump += obj.toString() + "<br/>\n";
        break;
      default:
        dump += "<br>\n";
        for(var key in obj){dump += level_nbsp +"<b>" + key + "</b> " + var_dump(obj[key], level + 1);}
        break;
    }
    if(level == 1){
      var dump_area = document.createElement('dump_area');
      dump_area.innerHTML = dump;
      document.body.appendChild(dump_area);
    }
    else{return dump;}
  }
</script>
The previous code will display:
(object) : 
     yes (number) : 1
     no (boolean) : false
     alert (function) : function alert() { [native code] }
     hello world (function) : function hello_world(){alert("Hello World!");}
Hope this helps.
If you’re a PHP developer, this article about an upgraded version of the PHP var_dump() function may interest you.
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s