Discover the various ways in JavaScript to inspect the content of an object (or any other value).

JavaScript offers several methods to inspect the content of a variable. Specifically, let’s explore how to print the content of an object.

Suppose we have the following object car, but we are uncertain about its content and wish 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 method is compatible with all browsers.

console.log

console.log(car)

Inspect object using console.log

console.dir

console.dir(car)

Inspect object using console.dir

This works similarly to

console.log('%O', car)

JSON.stringify()

This method prints the object as a string representation:

JSON.stringify(car)

Inspect object using console.dir

By adding these parameters:

JSON.stringify(car, null, 2)

you can format the output in a more visually appealing way. The last number determines the amount of indentation spaces:

Inspect object using console.dir

JSON.stringify() has the advantage of working outside of the console. You can print the object on the screen or combine it with the Console API to print it in the console:

console.log(JSON.stringify(car, null, 2))

Combine console.log with JSON.stringify

toSource()

Similar to JSON.stringify(), toSource() is a method available on most types, however, it is only supported in Firefox (and browsers based on it):

Using toSource

Despite its usefulness, toSource() is not a standard method and is only implemented in Firefox. Therefore, JSON.stringify() is a better solution.

Iterating through properties using a loop

The for...in loop is convenient for printing an object’s properties:

const inspect = obj => {
  for (const prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      console.log(`${prop}: ${obj[prop]}`)
    }
  }
}

inspect(car)

Loop through properties

In this example, hasOwnProperty() is used to avoid printing inherited properties.

You can decide what to do within the loop. Here, we print the property names and values to the console using console.log(). Alternatively, you can add them to a string and then print them on the page.

How to inspect in Node.js

The util package provides the inspect() method, which works well in Node.js:

util.inspect(car)

Use util.inspect in Node.js

However, a much better presentation is provided by console.dir() with the colors property enabled:

console.dir(car, { colors: true })

console.dir in Node with colors