How to Inspect a JavaScript Object
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.
- The Console API
JSON.stringify()
toSource()
- Iterating through properties using a loop
- How to inspect in Node.js
Suppose we have the following object car
, but we are uncertain about its content and wish to inspect it:
1 | const car = { |
The Console API
Using the Console API, you can print any object to the console. This method is compatible with all browsers.
console.log
1 | console.log(car) |
console.dir
1 | console.dir(car) |
This works similarly to
1 | console.log('%O', car) |
JSON.stringify()
This method prints the object as a string representation:
1 | JSON.stringify(car) |
By adding these parameters:
1 | 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:
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:
1 | console.log(JSON.stringify(car, null, 2)) |
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):
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:
1 | const inspect = obj => { |
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:
1 | util.inspect(car) |
However, a much better presentation is provided by console.dir()
with the colors
property enabled:
1 | console.dir(car, { colors: true }) |
tags: [“JavaScript”, “object”, “Console API”, “JSON.stringify”, “Node.js”, “inspect”, “loop”, “util”]