JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Object Display


In JavaScript, objects are collections of key–value pairs, used to represent structured data. Unlike primitive values (like numbers or strings), objects cannot be directly converted into a readable string for display. Attempting to display an object using alert() or concatenation often results in [object Object].

Understanding how to display objects properly is crucial for:

  • Debugging during development

  • Rendering object data on web pages

  • Logging or storing object data in a readable format

  • Working with dynamic data from APIs or databases

In this tutorial, we will explore multiple ways to display objects, from simple console output to advanced DOM rendering, including nested objects and arrays.

1. Displaying Objects Using console.log()

The simplest method for inspecting objects is using the browser console:

const person = { firstName: "John", lastName: "Doe", age: 25 };
console.log(person);
  • Modern browsers display objects in an expandable tree structure.

  • Nested objects can be expanded to view all properties.

Example with Nested Objects

const student = {
  name: "Alice",
  marks: { math: 90, science: 85 }
};

console.log(student);
  • You can expand marks to see individual scores.

  • console.log() is ideal for debugging and development, but it doesn’t work for user-facing display on web pages.

Tip: Use console.table(student.marks) to display objects in a tabular format.

2. Displaying Objects Using alert()

Using alert() directly on an object displays [object Object]:

alert(person); // [object Object]

This happens because JavaScript calls the object's toString() method, which by default returns [object Object].

To display the object in a readable format, we need to convert it into a string using JSON.stringify().

3. Using JSON.stringify()

JSON.stringify() converts an object into a JSON-formatted string:

alert(JSON.stringify(person));

Output:

{"firstName":"John","lastName":"Doe","age":25}

Pretty Printing

You can make it more readable by adding indentation:

alert(JSON.stringify(person, null, 2));

Output:

{
  "firstName": "John",
  "lastName": "Doe",
  "age": 25
}
  • The second parameter null indicates no transformation of properties.

  • The third parameter 2 specifies two spaces of indentation.

Tip: Pretty printing is very useful when displaying nested objects or debugging API responses.

4. Displaying Objects on a Web Page

Using document.write()

document.write(JSON.stringify(person, null, 2));
  • Shows the object directly on the page in JSON format.

  • Caution: document.write() can overwrite the page content if used after the page has loaded.

Using DOM Manipulation (Recommended)

You can dynamically render object properties in HTML elements:

<div id="output"></div>
<script>
const person = { firstName: "John", lastName: "Doe", age: 25 };
const container = document.getElementById("output");
container.innerHTML = `
  First Name: ${person.firstName} <br>
  Last Name: ${person.lastName} <br>
  Age: ${person.age}
`;
</script>
  • Allows formatted, styled, and interactive display.

  • Suitable for real-world applications instead of document.write().

5. Displaying Dynamic Properties

If the object properties are unknown or dynamic, you can loop through them using for...in or Object.entries().

Using for...in

let output = "";
for (let key in person) {
  output += `${key}: ${person[key]}<br>`;
}
document.getElementById("output").innerHTML = output;

Using Object.entries()

let html = "";
Object.entries(person).forEach(([key, value]) => {
  html += `${key}: ${value}<br>`;
});
document.getElementById("output").innerHTML = html;

Both approaches work well for unknown or changing objects, such as API responses.

6. Displaying Arrays of Objects

Often, you need to display arrays of objects:

const students = [
  { name: "Alice", age: 20 },
  { name: "Bob", age: 22 }
];

let html = "";
students.forEach(student => {
  html += `Name: ${student.name}, Age: ${student.age}<br>`;
});
document.getElementById("output").innerHTML = html;
  • Useful for displaying lists, tables, or dynamic content.

  • Can be combined with HTML templates for professional layouts.

7. Notes and Best Practices

  • Use console.log() for development and debugging.

  • Use JSON.stringify() for alerts, debugging, or sending data to a server.

  • Use DOM manipulation for displaying objects on web pages safely.

  • Handle nested objects and arrays carefully when displaying.

  • Avoid document.write() in modern development.

  • For large objects, consider pretty printing or tabular display using console.table().

Summary of the Tutorial

  • Objects cannot be directly displayed as readable strings; [object Object] is default.

  • Use console.log() for debugging.

  • Use JSON.stringify() for string conversion, with optional pretty printing.

  • Use DOM manipulation for safe, styled, and dynamic display.

  • Loops (for...in, Object.entries()) allow dynamic property display.

  • Arrays of objects require iteration for rendering multiple entries.

  • Proper object display is crucial for debugging, web development, and API data handling.

Displaying JavaScript objects effectively ensures clear debugging, user-friendly UI, and maintainable code, making it a fundamental skill for all JavaScript developers.


Practice Questions

  1. Console Display
    Create an object person with firstName, lastName, and age. Display it in the console using console.log().

  2. Alert Display
    Use alert() to display the same person object. Observe what is shown and explain why.

  3. JSON.stringify()
    Convert the person object into a JSON string using JSON.stringify() and display it with alert().

  4. Pretty Printing
    Display the person object in an alert with formatted JSON (indentation of 2 spaces).

  5. DOM Display Using innerHTML
    Create a <div> with id="output". Display the person object’s properties inside this div using innerHTML and template literals.

  6. Dynamic Property Display
    Use a for...in loop to display all properties of the person object dynamically in the output div.

  7. Using Object.entries()
    Use Object.entries() to iterate over the person object and display key-value pairs in the div.

  8. Array of Objects Display
    Create an array of student objects, each with name and age. Use forEach to display all students in the div with a formatted string.

  9. Nested Object Display
    Create a student object with a nested marks object. Display all properties, including nested marks, in a readable format on the page.

  10. Console Table Display
    Use console.table() to display the array of student objects created in question 8 in a tabular format in the console.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top