Print Object To Screen

Avatar of Chris Coyier
Chris Coyier on

PHP has a nice print_r function for printing out information about a variable to the screen. console.log() is great for that in JavaScript also, but sometimes you just need/want to look at it on the screen.

function print_r(o) {
  return JSON.stringify(o,null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;'); 
}

So if you have an object like:

var myObject = {
   "lunch": "sandwich",
   "dinner": "stirfry"
};

You could do:

var putHere = document.getElementById("#put-here");

putHere.innerHTML = print_r(myObject);

to see the result on screen.

Also, console.table() is sometimes much better than console.log() for this kind of thing.