browniebroke.com

Javascript console.log() object string substitution

November 27, 2024
Edit on Github

A common issue with Javascript’s console.log is that if you log a template string that contains a complex JS object, you’ll get a useless output:

>> const obj = { test: 1 }
>> console.log(`obj=${obj}`)
obj=[object Object]
>> console.log('obj=%s', obj)
obj=[object Object]

I was trying to debug something and copilot suggested to use %j formatting which seemed promising:

>> console.log('obj=%j', obj)
obj=%j
Object { test: 1 }

Unfortunately that was an hallucination, the %j isn’t doing anything, and is still present in the printed string.

That got me curious, so I looked it up online and found the dedicated MDN page with the %o substitution:

>> console.log('obj=%o', obj)
obj=Object { test: 1 }

Liked it? Please share it!

© 2024, Built with Gatsby