How to inspect JavaScript objects

Find out the way JavaScript provides you to inspect the object (or any other type of value)

JavaScript provides many ways to check the contents of variables. Especially let us find outHow to print the contents of an object.

Suppose we have this objectcar, But we don’t know its content and we want to check it:

const car = {
  color: 'black',
  manufacturer: 'Ford',
  model: 'Fiesta'
}

Console API

useConsole APIYou can print any object to the console. This will work in any browser.

console.log

console.log(car)

Inspect object using console.log

console.dir

console.dir(car)

Inspect object using console.dir

It's exactly like

console.log('%O', car)

JSON.stringify()

This prints the object as a string representation:

JSON.stringify(car)

Inspect object using console.dir

By adding the following parameters:

JSON.stringify(car, null, 2)

You can make it print better. The last number determines the number of spaces in the indentation:

Inspect object using console.dir

JSON.stringify()You can do it outside the console because you can print objects on the screen. Or you can combine it with the console API to print 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,Only in Firefox(And the browser based on it):

Using toSource

It is worth mentioning that JSON.stringify is a better solution, but it is not a standard and can only be implemented in Firefox.

Use loop iteration properties

Thisfor...inThe loop is convenient because it shows the object properties:

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

inspect(car)

Looping properties

I usehasOwnProperty()Avoid printing inherited attributes.

You can decide what to do in the loop, here we use the following command to print the attribute name and value to the consoleconsole.log, But you can add them to the string and then print it on the page.

How to check in Node.js

The inspect() method exposed by this methodutilThis package works well in Node.js:

util.inspect(car)

Use util.inspect in Node.js

However, byconsole.dir(),versuscolorsAttributes enabled:

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

console.dir in Node with colors

Download mine for freeJavaScript beginner's manual


More js tutorials: