Q:

How to Display a JavaScript Object

0

How to Display a JavaScript Object

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use console.log() or JSON.stringify() Method

You can use the console.log() method, if you simply wants to know what's inside an object for debugging purpose. This method will print the object in browser console.

// Sample object
var obj = {name: "John", age: 28, gender: "Male"};

// Printing object in console
console.log(obj);

To open the dedicated Console panel: Press Ctrl+Shift+J (Windows / Linux) or Cmd+Opt+J (Mac).

Alternatively, you can also use the JSON.stringify() method to print the object either on a web page or browser console. Let's try out the following example and see how it works:

// Sample object
var obj = {name: "John", age: 28, gender: "Male"};

// Converting object to JSON string
var str = JSON.stringify(obj);

// Printing the string
document.write(str);
console.log(str);

For nicely indented output, you can optinally pass replacer and space parameters, as shown below:

// Sample object
var obj = {name: "John", age: 28, gender: "Male"};

// Converting object to JSON string
var str = JSON.stringify(obj, null, 4); // indented with 4 spaces

// Printing the string
document.getElementById("output").innerHTML = str;
console.log(str);

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Add a Key/Value Pair to an Object in Javasc... >>
<< How to Loop Through a JavaScript Object...