Skip to content

How to print object in JavaScript | Example code

  • by

You can print objects using Window.alert() or console.log() or console.dir() function in JavaScript.

Print objects in JavaScript

Simple example code.

Using Window.alert() function

This method will display [object Object] as the output. You have to convert the object into a string first using the JSON.stringify() method.

<!DOCTYPE html>
<html>

<body>

  <script>
   var obj = [
   { name: 'Max', age: 23 },
   { name: 'John', age: 20 },
   { name: 'Caley', age: 18 }
   ];
   
   alert(JSON.stringify(obj, null, 4));

 </script>

</body>
</html> 

Output:

How to print object in JavaScript

Using console.log() function

This method is often used for debugging without irritating alerts and can be used to print an object’s contents.

<script>
   var obj = [
   { name: 'Max', age: 23 },
   { name: 'John', age: 20 },
   { name: 'Caley', age: 18 }
   ];

   console.log(obj)

</script>

Using console.dir() function

It displays all the properties of the specified JavaScript object in the web console.

<script>
   var obj = [
   { name: 'Max', age: 23 },
   { name: 'John', age: 20 },
   { name: 'Caley', age: 18 }
   ];

   console.dir(obj)

</script>

Note: The actual difference between console.dir() and console.log() comes when printing the DOM elements to the console.

How to print all the properties of the object in JavaScript?

Answer: Generally you can do that with a console log.

console.log(object);

Or use The Object.keys() function to get an array of the properties of the object:

var obj = { name: 'Harry', age: '25', sex: 'male'};
Object.keys(obj).forEach((prop)=> console.log(prop));

If you want a pretty good-looking output use JSON.stringify

console.log(JSON.stringify(object, null, 4));

Where the second argument alters the contents of the string before returning it. The third argument specifies how many spaces to use as white space for readability.

Do comment if you have any doubts or suggestions on this Js print topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading