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!

Jon Portella
JavaScript in Plain English

--

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.

🔛

Illustration by my buddy Loor Nicolas

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] :

Console.log: Hidden third level as friend: [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:

  1. Functions will disappear from the output.
  2. You won’t get syntax highlighting, as you’re basically logging a formatted string.
JSON.stringify: no colors and… where’s is sayHi()??

A (BETTER) SOLUTION

Use console.dir(person, {depth: null}), that will show all nested objects, including functions, with syntax highlighting.

Console.dir(person, {depth: null})

--

--