What is util.inspect() in Node.js?

Nodejs provides a utility function for debugging called util.inspect(). util.inspect() returns a string representation of the object passed as a parameter and especially comes in handy while working with large complex objects.

Protoype

util.inspect(object[, showHidden[, depth[, colors]]])

Parameters

  • object: The object that needs to be inspected.
  • options:
    • depth: Determines the number of times to recurse through the object and show the nested objects within. depth defaults to 22; however, if the object needs to be completely shown at max depth level, then depth can be set to Infinity or null.
    • color: A boolean which, if set to true, colorizes the output with ANSI color codes. These colors are customizable. color defaults to false.
    • showhidden: It is a boolean that determines whether the object’s non-enumerable properties and methods are to be shown. showhidden is set to false by default.

A full list of arguments is available in the official documentation

Return value

util.inspect() returns a string representation of the object.

Code

var util = require('util');
let object = {
a : 1,
b : 2,
c : {
d : {
e: {
f: {
x: 99,
y: 100
}
}
},
g : 5
},
h: 6
}
console.log(util.inspect(object, depth=null, color=true));
console.log(util.inspect(object, depth=2, color=false));

The code above shows a basic example of the use of util.inspect(). Notice that setting the depth to null causes the function to recursively output the entire object including all the nested objects, while setting the parameter color to true shows the output in a prettier format.

To demonstrate the use of the showHidden parameter, we can pass the console object in the util.inspect() function with the showHidden attribute set to true and false, respectively.

const util = require('util')
console.log("showHidden = false")
console.log(util.inspect(console, showHidden = false));
console.log("\nshowHidden = true\n")
console.log(util.inspect(console, showHidden = true))

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved