JavaScript Object Display

Displaying JavaScript objects is not as straightforward as displaying strings or numbers. JavaScript provides several ways to display object contents: JSON.stringify(), looping through properties, Object.values(), and console methods like console.table().

JSON.stringify()

JSON.stringify() converts a JavaScript object into a JSON string. This is the most common way to display an object's contents. You can use the third parameter for pretty-printing with indentation.

JSON.stringify()
let person = {
  name: "Alice",
  age: 30,
  hobbies: ["reading", "coding"],
  address: { city: "NYC", zip: "10001" }
};

// Basic stringify
console.log(JSON.stringify(person));

// Pretty-print with 2-space indent
console.log(JSON.stringify(person, null, 2));

// With replacer function (filter properties)
let filtered = JSON.stringify(person, ["name", "age"]);
console.log(filtered);

// Stringify with replacer function
let custom = JSON.stringify(person, (key, value) => {
  if (typeof value === "number") return value * 2;
  return value;
}, 2);
console.log(custom);

Looping with Object.values()

Object.values() returns an array of the object's own property values. You can use it with forEach, map, or any array method to display or process each value.

Object.values() Loop
let scores = {
  math: 95,
  science: 88,
  english: 92,
  history: 85
};

// Display all values
let values = Object.values(scores);
console.log("Values:", values);

// Calculate average
let avg = values.reduce((sum, v) => sum + v, 0) / values.length;
console.log("Average:", avg);

// Display with keys
Object.entries(scores).forEach(([subject, score]) => {
  console.log(`${subject}: ${score}`);
});

for...in Loop

The for...in loop iterates over all enumerable properties of an object, including inherited ones. Use hasOwnProperty() to filter out inherited properties when needed.

for...in Loop
let car = {
  brand: "Toyota",
  model: "Camry",
  year: 2024
};

// for...in iterates over property names
for (let key in car) {
  console.log(`${key}: ${car[key]}`);
}

// Filter with hasOwnProperty
console.log("--- Own properties only ---");
for (let key in car) {
  if (car.hasOwnProperty(key)) {
    console.log(`${key}: ${car[key]}`);
  }
}

// Building a display string
let display = "";
for (let key in car) {
  display += `${key}=${car[key]} `;
}
console.log(display.trim());

Custom toString() Override

By default, converting an object to a string produces '[object Object]'. You can override the toString() method to provide a meaningful string representation of your object.

toString() Override
// Default toString
let obj = { a: 1, b: 2 };
console.log(String(obj));
console.log(`Object: ${obj}`);

// Custom toString
let person = {
  name: "Alice",
  age: 30,
  toString() {
    return `Person(${this.name}, ${this.age})`;
  }
};

console.log(String(person));
console.log(`Who: ${person}`);

// Custom toString on a constructor
function Point(x, y) {
  this.x = x;
  this.y = y;
  this.toString = function() {
    return `(${this.x}, ${this.y})`;
  };
}

let p = new Point(10, 20);
console.log(`Point: ${p}`);

console.table()

console.table() displays objects and arrays as a formatted table in the console. It is excellent for debugging, especially with arrays of objects or objects with many properties.

console.table()
// Display an object as a table
let user = {
  name: "Alice",
  age: 30,
  role: "developer"
};
console.table(user);

// Display array of objects
let users = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 25 },
  { name: "Charlie", age: 35 }
];
console.table(users);

// Select specific columns
console.table(users, ["name"]);
MethodOutputBest For
JSON.stringify()JSON stringSerialization, logging
JSON.stringify(o,null,2)Pretty JSON stringReadable display
Object.values()Array of valuesProcessing values
Object.entries()Array of [key, val]Key-value iteration
for...inEach property keyGeneral iteration
toString() overrideCustom stringString contexts
console.table()Formatted tableDebugging
📝 Note: JSON.stringify() cannot handle all values: functions, undefined, and Symbol are omitted. Circular references cause an error. For deep debugging, use console.dir() with depth options, or a library like util.inspect() in Node.js.
Exercise:
What does JSON.stringify() do with a function property?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.