The Right Way To Log Objects in Node.js

March 01, 2021

0

Illustration by my buddy Loor Nicolas


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

1

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.

2

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.

3


Written by Jon Portella.