Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Print Object To Screen

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.

Comments

  1. Ben Caplan
    Permalink to comment#

    Great tip Chris! echo '<pre>'; print_r($var); echo '</pre>';is one of the best PHP tools. I use it all the time and I always wished that JS had a comparable method (outside of the console).

    I think that in your last JS code block the ‘#’ in your .getElementById(), should not be there. Also unless I am missing something the first code block is plain old vanilla JS (not jQuery).

    In either case, thanks as always for the awesome tips!

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```