How to inspect a JavaScript object
By Flavio Copes
Learn how to inspect a JavaScript object using console.log, console.dir, JSON.stringify(), a for...in loop, and util.inspect from the Node util module.
JavaScript offers many ways to inspect the content of a variable. In particular, let’s find out how to print the content of an object.
Let’s say we have this object car, but we don’t know its content, and we want to inspect it:
const car = {
color: 'black',
manufacturer: 'Ford',
model: 'Fiesta'
}
The Console API
Using the Console API you can print any object to the console. This will work on any browser.
console.log
console.log(car)

console.dir
console.dir(car)

This works exactly like
console.log('%O', car)
JSON.stringify()
This will print the object as a string representation:
JSON.stringify(car)

By adding these parameters:
JSON.stringify(car, null, 2)
you can make it print more nicely. The last number determines the amount of spaces in indentation:

JSON.stringify() has the advantage of working outside of the console, as you can print the object in the screen. Or, you can combine it with the Console API to print this in the console:
console.log(JSON.stringify(car, null, 2))

Firefox used to have a similar non-standard toSource() method. It was never available in other browsers and Firefox removed it in version 74, so JSON.stringify() is the way to go.
Iterate the properties using a loop
The for...in loop is handy, as it prints the object properties:
const inspect = obj => {
for (const prop in obj) {
if (Object.hasOwn(obj, prop)) {
console.log(`${prop}: ${obj[prop]}`)
}
}
}
inspect(car)

I use Object.hasOwn() to avoid printing inherited properties. You will also see obj.hasOwnProperty(prop) in older code (that’s what the screenshot shows). It does the same thing, but Object.hasOwn() also works on objects created with Object.create(null), which have no hasOwnProperty method.
You can decide what to do in the loop, here we print the properties names and values to the console using console.log, but you can adding them to a string and then print them on the page.
How to inspect in Node.js
The inspect() method exposed by the util package works great in Node.js:
import util from 'node:util'
util.inspect(car)
It returns the object as a string, { color: 'black', manufacturer: 'Ford', model: 'Fiesta' }, which you can print or log.
But, a much better presentation is provided by console.dir(), with the colors property enabled:
console.dir(car, { colors: true })
This prints the same object, with the property values colored, like the browser console does.
Want me to talk about your product? You can sponsor this site.
Related posts about js: