While not part of the language, the browser and Node.js (the 2 main environment in which we execute JavaScript code) expose the Console API, to which we can access using the console
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'
}
Using the Console API you can print any object to the console. This will work on any browser. You can open the console in the browser in Firefox using the Tools -> Web Developer -> Web Console menu.
Here are the main ways to use it.
console.log
console.log(car)
console.dir
console.dir(car)
This works exactly like
console.log('%O', car)
When debugging in Node.js you can add the colors
property to print the object nicely:
console.dir(car, { colors: true })
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))
toSource()
Similar to JSON.stringify, toSource() is a method available on most types, only in Firefox (and browsers based on it):
Worth mentioning, but not being a standard, and only being implemented in Firefox, makes JSON.stringify a better solution.
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 (obj.hasOwnProperty(prop)) {
console.log(`${prop}: ${obj[prop]}`)
}
}
}
inspect(car)
I use hasOwnProperty()
to avoid printing inherited properties.
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.