OMBD#5: The Right Way To Log Objects in Node.js
And a few other methods that you can also use, but beware of the caveats!
Welcome to issue #5 of One Minute Better Developer, where you become a more successful software developer by reading short nuggets of knowledge, one minute at a time.
⏮️ 🔛 ⏭️
The problem
We want to log in to the console this deeply nested JavaScript Object:
A Naive Solution
The common beginner mistake is to just put it through the most basic logging tool that the language provides: console.log
. However, we have limited depth logging, makingfriend
on the third level just appear as [Object]
:
A Hacky Solution
A trick I’ve used in the past is to put it through JSON.stringify with two extra arguments: console.log(JSON.stringify(person, null, 2))
. You can read about what these do in MDN.
But this approach carries some problems:
- Functions will disappear from the output.
- You won’t get syntax highlighting, as you’re basically logging a formatted string.
A (BETTER) SOLUTION
Use console.dir(person, {depth: null})
, that will show all nested objects, including functions, with syntax highlighting.