March 01, 2021
Illustration by my buddy Loor Nicolas
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
}
}
}
}
}
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 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:
JSON.stringify: no colors and… where’s is sayHi()
??
Use
console.dir(person, {depth: null})
That will show all nested objects, including functions, with syntax highlighting.
Written by Jon Portella.