The Right Way To Log Objects in Node.js

March 01, 2021 • 2 min read

Presentation image

The problem

We want to log in to the console this deeply nested JavaScript Object:

const person = {
  name: "Joe",
  age: 24,
  sayHi: function () {
    console.log("Hi!");
  },
  friend: {
    name: "Sarah",
    age: 26,
    friend: {
      name: "Peter",
      age: 39,
      friend: {
        name: "Sarah",
        age: 26,
        friend: {
          name: "Annie",
          age: 21,
        },
      },
    },
  },
};

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

Presentation image

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.
Presentation image

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.

Presentation image

WDYT about this post? I read you here:

Get notified of new blog posts?

RSS FeedGet an Email

RSS is the correct choice, btw.