#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
3 min read
Question 20 of 62easy

How to use the util.inspect function?

Custom object inspection and formatting.

What You'll Learn

  • Inspecting objects
  • Customizing output
  • Custom inspect methods

Basic Usage

code.jsJavaScript
const util = require('util');

const obj = {
  name: 'John',
  nested: { a: 1, b: 2 },
  arr: [1, 2, 3]
};

// Default inspection
console.log(util.inspect(obj));

// With options
console.log(util.inspect(obj, {
  colors: true,       // Colorize output
  depth: null,        // Unlimited depth (default: 2)
  maxArrayLength: 100,// Max array elements
  showHidden: false,  // Show non-enumerable
  compact: false      // Multi-line output
}));

Shorthand

code.jsJavaScript
// console.dir uses util.inspect
console.dir(obj, { depth: null, colors: true });

Custom Inspect Method

code.jsJavaScript
const util = require('util');

class User {
  constructor(name, password) {
    this.name = name;
    this.password = password; // Sensitive!
  }

  // Custom inspect - hide password
  [util.inspect.custom](depth, opts) {
    return `User { name: '${this.name}', password: [HIDDEN] }`;
  }
}

const user = new User('John', 'secret123');
console.log(user);
// User { name: 'John', password: [HIDDEN] }

Inspect Defaults

code.jsJavaScript
// Set global defaults
util.inspect.defaultOptions.depth = null;
util.inspect.defaultOptions.colors = true;