iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Object Display

JavaScript objects have several string-ish representations. Knowing which to use saves you from "[object Object]" surprises.

Three ways to render an object

MethodReturnsUse it for
String(obj) or `${obj}`The result of obj.toString() — usually "[object Object]"Debugging only.
JSON.stringify(obj)A JSON textLogging, persistence, API bodies.
console.log(obj)Interactive tree in DevToolsDebugging.
console.table(arrOrObj)Tabular renderingLists of records.

Custom toString

JS
const money = {
  amount: 1599,
  currency: "USD",
  toString() { return `$${(this.amount / 100).toFixed(2)}`; },
};

`${money}`;          // "$15.99"
String(money);       // "$15.99"
JSON.stringify(money);   // '{"amount":1599,"currency":"USD"}'

Convert in & out of JSON

JS
// Object → JSON string
const text = JSON.stringify(user);

// Pretty print
JSON.stringify(user, null, 2);

// JSON string → object
const parsed = JSON.parse(text);

// Filter properties on the way out
JSON.stringify(user, ["id", "name"]);                       // allowlist
JSON.stringify(user, (k, v) => k === "password" ? undefined : v);   // replacer

Listing properties for display

JS
for (const [key, value] of Object.entries(user)) {
  console.log(`${key}: ${value}`);
}
Tip: In DevTools, console.dir(obj) shows the prototype chain too — useful when debugging class hierarchies.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from Object Display!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Convert an object to a 2-space indented JSON string.

const text = JSON. (obj, null, 2);

Test yourself

Q1. `${user}` typically prints…
Q2. Render an object usefully with…
Q3. console.dir shows…

Discussion

Loading…