Creative Designs Guru

How to Avoid console.log display [object Object]

December 22, 2020

As a JavaScript developer, you need to print an object value by using console.log. With console.log, the function sometimes returns [object Object] for a complex object and it isn't what you want.

First solution: continue to use console.log

There is a workaround to solve this situation with console.log. The first one is to convert the object to a string by using JSON.stringify(). Here is an example:

console.log(JSON.stringify(randomVariable));

There are two drawbacks to this solution:

  • it's pretty annoying to type console.log and JSON.stringify
  • the output is not pretty print, it's very hard to read when the object is complex and has several attributes.

Second solution: console.dir

As a better alternative, you can use console.dir and it solves the two previous drawbacks. Here is an example of how to use console.dir:

console.dir(randomVariable);

It's extremely short to type and the output is pretty printed on your favorite browser console. Indeed, console.dir displays as a tree and you can easily read the object attribute.

A screenshot example with console.dir:

console.dir outputs tree object