WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to Display a JavaScript Object

Topic: JavaScript / jQueryPrev|Next

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);

If you open the browser console you'll see the output that looks something like this figure.

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);

See the tutorial on JavaScript Objects to learn more about creating and manipulating objects.


Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties