Question
How can I display the contents of a JavaScript object in a string format, similar to how alert() displays a variable? I would like the object's properties and values to appear in a readable, formatted way.
Short Answer
You will learn why JavaScript objects do not automatically become readable strings, how to inspect them while debugging, and how to convert them to formatted text with JSON.stringify() when appropriate.
Concept
JavaScript objects store related values as property–value pairs:
const user = {
name: "Ava",
age: 28
};
An object is a structured value, not a plain string. When JavaScript must turn it into text automatically, such as in this code:
alert(user);
it usually uses the object's default string representation:
[object Object]
That output confirms there is an object, but it does not show its contents.
For debugging, use console.log() because browser developer tools can inspect objects interactively. To create text that can be displayed in an alert, page element, log message, or API payload, use JSON.stringify().
JSON.stringify() converts JSON-compatible object data into a string. Its optional third argument can add indentation, making the result easier to read.
Mental Model
Think of an object as a labeled storage box:
- The labels are property names, such as
nameandage. - The contents are values, such as
"Ava"and28.
alert() is designed to show a single line of text. If you hand it the whole storage box, it only says, “this is an object” ([object Object]).
JSON.stringify() is like writing an inventory list of the box: it lists each label and its value in text form.
Syntax and Examples
Use console.log() to inspect an object during development:
const product = {
name: "Notebook",
price: 4.99,
inStock: true
};
console.log(product);
Open the browser's developer tools and look at the Console. You can usually expand the object to inspect nested values.
Use JSON.stringify() when you need a string:
const product = {
name: "Notebook",
price: 4.99,
inStock: true
};
const text = JSON.stringify(product);
alert(text);
This produces a compact string:
{"name":"Notebook","price":4.99,"inStock":true}
For readable, multi-line formatting, pass null as the replacer and 2 as the indentation size:
alert(JSON.stringify(product, null, 2));
Output:
{
"name": "Notebook",
"price": 4.99,
"inStock": true
}
To show the result on a web page, use textContent rather than innerHTML:
const output = document.querySelector("#output");
output.textContent = JSON.stringify(product, null, 2);
A <pre id="output"></pre> element is useful because it preserves line breaks and indentation.
Step by Step Execution
Consider this code:
const account = {
owner: "Sam",
balance: 120,
active: true
};
const displayText = JSON.stringify(account, null, 2);
console.log(displayText);
accountis created as an object with three properties.JSON.stringify(account, null, 2)reads its JSON-compatible properties.nullmeans no custom filtering or conversion function is being used.2tells JavaScript to indent nested lines with two spaces.- The resulting string is assigned to
displayText. console.log(displayText)prints that string:
{
"owner": "Sam",
"balance": 120,
"active": true
}
Unlike console.log(account), this is already text. You can pass it to alert(), assign it to textContent, or send it in a JSON-based request.
Real World Use Cases
Displaying object data as text is useful in several situations:
- Debugging API responses: Log returned data to see its shape and values.
console.log(responseData); - Temporary diagnostics: Show formatted configuration data while testing an app.
console.log(JSON.stringify(config, null, 2)); - Admin and support tools: Render a JSON preview in a
<pre>element. - Saving data: Convert JSON-compatible objects to strings before storing them in
localStorage.localStorage.setItem("settings", JSON.stringify(settings)); - Network requests: Send structured data to an API as JSON.
fetch("/api/orders", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(order) });
Real Codebase Usage
In real projects, developers choose the display method based on the goal.
Inspect values while debugging
Use console.log(object) when you want to explore the object in developer tools:
console.log("Received user:", user);
For a fixed snapshot, stringify it first. This can be helpful because developer tools may display a live object whose values change later:
console.log("User snapshot:", JSON.stringify(user, null, 2));
Validate before displaying or serializing
Guard against missing data:
function formatUser(user) {
if (!user || typeof user !== "object") {
return "No user data available.";
}
return JSON.stringify(user, null, 2);
}
Show safe text in the interface
When rendering diagnostic data, assign to textContent:
function showDebugData(data) {
document.querySelector("#debug-output").textContent =
JSON.stringify(data, null, 2);
}
Avoid using innerHTML for ordinary text data. textContent treats the result as text rather than markup.
Use custom display text for users
Raw JSON is useful for developers, but users usually need a designed message:
const message = `${user.name} has ${user.points} points.`;
This is clearer than displaying the entire object.
Common Mistakes
Expecting alert(object) to show properties
const user = { name: "Ava" };
alert(user); // [object Object]
Fix: Explicitly create a string.
alert(JSON.stringify(user, null, 2));
Using JSON.parse() instead of JSON.stringify()
JSON.parse() goes in the opposite direction: it turns a JSON string into an object.
const user = { name: "Ava" };
JSON.parse(user); // Incorrect: user is already an object
Fix: Use JSON.stringify() to convert an object to text.
const text = JSON.stringify(user);
Assuming every object can be stringified
Circular references cause an error:
const person = { name: "Ava" };
person.self = person;
JSON.stringify(person); // TypeError: Converting circular structure to JSON
Fix: Remove or avoid circular references before serializing, or use a specialized debugging approach. For simple objects, console.log(person) can still help with inspection.
Being surprised when values disappear or change
JSON does not represent every JavaScript value. For example, object properties whose values are undefined or functions are omitted:
const item = {
name: "Pen",
discount: undefined,
calculateTotal() {
return 10;
}
};
console.log(JSON.stringify(item));
// {"name":"Pen"}
Use JSON for data, not for preserving every JavaScript-specific feature.
Showing unformatted JSON when readability matters
alert(JSON.stringify(user));
This works but can be hard to read for nested objects. Use indentation:
alert(JSON.stringify(user, null, 2));
Treating an alert as a normal UI component
alert() blocks the page and interrupts the user. It is acceptable for quick testing, but use a page element, modal, or notification component in a finished application.
Comparisons
| Approach | Best use | Result | Limitation |
|---|---|---|---|
alert(object) | Almost never for objects | Usually [object Object] | Does not reveal properties |
console.log(object) | Debugging in developer tools | Expandable object inspection | Not visible to normal users |
JSON.stringify(object) | Creating JSON text | Compact one-line string by default | Fails on circular references; skips some values |
JSON.stringify(object, null, 2) | Readable debugging or <pre> output | Indented multi-line JSON string | Still has JSON limitations |
| Template literal | Displaying selected fields to users | Custom message | You must choose each property yourself |
Example of a user-focused template literal:
const user = { name: "Ava", age: 28 };
const message = `${user.name} is ${user.age} years old.`;
Cheat Sheet
// Inspect an object in developer tools
console.log(object);
// Convert an object to compact JSON text
const text = JSON.stringify(object);
// Convert an object to readable, indented JSON text
const prettyText = JSON.stringify(object, null, 2);
// Display formatted object text temporarily
alert(JSON.stringify(object, null, 2));
// Display formatted object text on a page
outputElement.textContent = JSON.stringify(object, null, 2);
Key rules:
- Objects are structured values; they are not automatically readable strings.
JSON.stringify()converts JSON-compatible data to a string.JSON.parse()converts JSON text back into an object.- Use
console.log()for debugging and exploration. - Use
textContentto render text safely in the DOM. JSON.stringify()throws for circular references.- Functions and
undefinedobject properties are not included in JSON output.
FAQ
Why does alert show [object Object] in JavaScript?
alert() needs text. When given a plain object, JavaScript uses its default text conversion, which is typically [object Object].
How do I print an object nicely in JavaScript?
Use:
console.log(JSON.stringify(object, null, 2));
The 2 adds two-space indentation.
Is console.log(object) better than JSON.stringify(object)?
For debugging, often yes. console.log(object) lets you inspect and expand the object in developer tools. Use JSON.stringify() when you specifically need a string.
Can I use JSON.stringify in alert()?
Yes:
alert(JSON.stringify(object, null, 2));
It is useful for quick testing, though alert() is not ideal for finished user interfaces.
Why does JSON.stringify omit some properties?
JSON only supports JSON data types. In object properties, undefined, functions, and symbols are omitted. Other values, such as Date, may be converted to a JSON-compatible representation.
Why does JSON.stringify throw a circular structure error?
A circular reference occurs when an object eventually points back to itself. JSON cannot represent that loop.
How can I display an object in HTML?
Put the formatted string in an element's textContent, preferably a <pre> for preserved formatting:
document.querySelector("#output").textContent = JSON.stringify(data, null, 2);
Mini Project
Description
Build a small object inspector for a settings panel. A user clicks a button and the app displays a readable JSON preview of the current settings. This mirrors a simple debugging or admin-tool feature.
Goal
Render a JavaScript object's contents as formatted text in the browser without using alert().
Requirements
Create an object containing at least three settings properties.
Add a button that displays the object when clicked.
Show the object as indented JSON in a <pre> element.
Use JSON.stringify() with two-space indentation.
Use textContent to place the result in the page.
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.