This post will discuss how to print the contents of an object in JavaScript.

1. Using Window.alert() function

The Window.alert() method displays a dialog with the specified content.

Printing an object using the Window.alert() method will display [object Object] as the output. To get the proper string representation of the object, the idea is to convert the object into a string first using the JSON.stringify() method.

To pretty-print it, specify the total number of space characters to use as white space in the third argument with the second argument undefined.

2. Using console.log() function

The console.log() is a standard method to print a message to the web console. This method is often used for debugging without irritating alerts and can be used to print an object’s contents.

Download  Run Code

 
MDN recommends using console.log(JSON.parse(JSON.stringify(obj))) over console.log(obj) for printing objects. This is done to avoid constant updates to the console whenever the value of the object changes.

This method won’t work if you try to concat a string with the object, as shown below:

Download  Run Code

 
The correct way is to pass the message as the first parameter and the object as the second parameter to the log method.

Download  Run Code

3. Using console.dir() function

The console.dir() displays all the properties of the specified JavaScript object in the web console.

Download  Run Code

 
The actual difference between console.dir() and console.log() comes when printing the DOM elements to the console. The console.log gives special treatment to DOM elements and prints the element in an HTML-like tree, whereas console.dir prints the element in a JSON-like tree.

 
With the Firefox browser, you can use the non-standard method Object.toSource() to print objects using any of the above-mentioned methods.

That’s all about printing the contents of an object in JavaScript.