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.
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:
console.log
and JSON.stringify
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
: