0
0
JavascriptHow-ToBeginner · 3 min read

How to Print Object in JavaScript: Simple Methods Explained

To print an object in JavaScript, use console.log(object) to display it in the console. For a readable string format, use JSON.stringify(object) which converts the object into a string.
📐

Syntax

console.log(object): Prints the object directly to the browser console or terminal.

JSON.stringify(object): Converts the object into a JSON string for readable output.

javascript
console.log(object);

console.log(JSON.stringify(object));
💻

Example

This example shows how to print an object using console.log and how to convert it to a string with JSON.stringify for clearer output.

javascript
const person = { name: "Alice", age: 25, city: "New York" };

// Print object directly
console.log(person);

// Print object as string
console.log(JSON.stringify(person));
Output
{ name: 'Alice', age: 25, city: 'New York' } {"name":"Alice","age":25,"city":"New York"}
⚠️

Common Pitfalls

Using console.log prints the object but may show it as expandable in some consoles, which can be confusing if the object changes later.

Using JSON.stringify does not print functions or symbols and can throw errors if the object has circular references.

javascript
const obj = { a: 1 };
obj.self = obj; // circular reference

// This will throw an error:
// console.log(JSON.stringify(obj));

// Correct way to handle circular references:
function safeStringify(obj) {
  const seen = new WeakSet();
  return JSON.stringify(obj, (key, value) => {
    if (typeof value === "object" && value !== null) {
      if (seen.has(value)) return "[Circular]";
      seen.add(value);
    }
    return value;
  });
}

console.log(safeStringify(obj));
Output
{"a":1,"self":"[Circular]"}
📊

Quick Reference

MethodDescriptionNotes
console.log(object)Prints object to consoleShows expandable object in dev tools
JSON.stringify(object)Converts object to JSON stringDoes not include functions or symbols
Custom stringify with replacerHandles circular referencesAvoids errors with circular objects

Key Takeaways

Use console.log(object) to print objects directly in JavaScript.
Use JSON.stringify(object) to get a readable string representation of an object.
JSON.stringify does not include functions or symbols and can fail on circular references.
Handle circular references with a custom replacer function in JSON.stringify.
Printing objects in the console may show live references that update if the object changes.