How to print javascript object to log

Often we need to print a javascript object to console log or somewhere else for debugging purpose. These are some handy ways to dump javascript object to log:

Dump javascript object using JSON.stringify

Outcome will be in console
<script type="text/javascript">
var obj = { k1:"v1", k2: "v2", k3: "v3"};
console.log("obj=" + JSON.stringify(obj));
</script>
Here is outcome (in console) from this code:

obj={"k1":"v1","k2":"v2","k3":"v3"}

Dump DOM object using “for…in” loop

In case object has properties.

Outcome will be in console
<script type="text/javascript">
var msg = "";
var obj = window.screen;
for (var i in obj) {
  msg += i + "=" + obj[i] + "\n"; 
}
console.log(msg);
</script>
Here is outcome (in console) from this code:

availWidth=1280
availHeight=773
width=1280
height=800
colorDepth=24
pixelDepth=24
availLeft=0
availTop=23
orientation=[object ScreenOrientation]

Dump objects using console format specifier

Here we’ll use %o (DOM object) and %O (Javascript object) in console.log

Outcome will be in console
<script type="text/javascript">
var obj = { k1:"v1", k2: "v2", k3: "v3"};
console.log("obj=%O", obj);
console.log("obj=%o", window.screen);
</script>
Here is outcome (in console) from this code:
console-log-format-js-and-dom-object

Note that console.log may not work in old IE browsers. So this should only be used in development/debugging environment.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments