@FahadM to JavaScriptEnglish • 7 days ago

How do you inspect and display a JavaScript object's contents cleanly?

message-square
0
1
How do you inspect and display a JavaScript object's contents cleanly?
@FahadM to JavaScriptEnglish • 7 days ago

The cleanest way to inspect a JavaScript object depends on whether you are debugging interactively in DevTools/Node or formatting output for logs, UI display, or error messages. console.dir() and console.table() shine for interactive inspection and uniform records, while JSON.stringify(obj, null, 2) (with a safe replacer for cycles, BigInt, or functions) produces clean, readable text for logs or display.


1. Interactive Inspection with console.dir() and console.table()

Use console.dir() when you want an expandable object representation—including getters, non-enumerable properties, or options like { depth: null } in Node.js—and console.table() when inspecting an array of objects or a flat dictionary with shared keys:

const serviceConfig = {
  name: "billing-worker",
  retries: 3,
  timeouts: { connectMs: 1500, readMs: 5000 }
};

// Full property tree in Node.js (or interactive tree in browser DevTools)
console.dir(serviceConfig, { depth: null, colors: true });

const jobs = [
  { id: "job-1", status: "ok", durationMs: 120 },
  { id: "job-2", status: "retry", durationMs: 480 }
];

console.table(jobs);

2. Readable String Formatting with JSON.stringify() (Cycle-Safe)

Plain console.log("State: " + obj) coerces objects to "[object Object]". Use JSON.stringify(value, replacer, 2) for formatted output, and guard against circular references or BigInt values when logging arbitrary runtime data:

function formatObjectForDisplay(value, space = 2) {
  const seen = new WeakSet();

  return JSON.stringify(
    value,
    (_, val) => {
      if (typeof val === "bigint") return `${val.toString()}n`; if (typeof val === "function") return `[Function: ${val.name || "anonymous"}]`;
      if (typeof val === "object" && val !== null) {
        if (seen.has(val)) return "[Circular]";
        seen.add(val);
      }
      return val;
    },
    space
  );
}

const user = { id: 42n, role: "admin" };
user.self = user;

console.log(formatObjectForDisplay(user));

3. Common Traps to Avoid

  • String-concatenating objects ("Data: " + obj): Template literals and + call .toString(), producing "[object Object]" instead of the object’s fields.
  • Calling JSON.stringify() blindly on cyclic or BigInt objects: Circular references throw a TypeError (Converting circular structure to JSON), and BigInt values also throw in JSON.stringify() unless handled in a replacer.
  • Using console.table() on deeply nested or irregular objects: It works best on uniform rows or shallow maps; deeply nested objects create noisy columns or index-heavy tables.

TL;DR: Use console.dir(obj, { depth: null }) or console.table() for interactive/tabular inspection, and JSON.stringify(obj, replacer, 2) with a WeakSet cycle check when rendering formatted text for logs or display.

Are you inspecting objects during local debugging, formatting payloads for structured logs/UI output, or dealing with circular references and BigInt fields?