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:
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
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": }, : .(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
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.(user);
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 |
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.
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 is not ideal for finished user interfaces.
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.