Skip to content

Console log object in JavaScript | Multiple ways

The basic method is used console.log(object) to console log objects in JavaScript. The Console method log() outputs a message to the web console.

console.log(obj)

Note: you must only log the object. For example, this won’t work:

console.log('My object : ' + obj)

Note: You can also use a comma in the log method, then the first line of the output will be the string and after that, the object will be rendered:

console.log('My object: ', obj);

Source: stackoverflow.com/

Console log object in JavaScript

Simple example code using console log.

<!DOCTYPE html>
<html>
<body>

  <script>
   var obj = {
    prop1: 'prop1Value',
    prop2: 'prop2Value',
    child: {
      childProp1: 'childProp1Value',
    },
  }
  console.log(obj)     
</script>

</body>
</html>

Output:

Console log object in JavaScript

Other Methods

Use native JSON.stringify method. Works with nested objects and all major browsers support this method. JSON.stringify(object) only works with JSON-compatible data, which means certain value types can be lost.

str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.

console.log(str); // Logs output to dev tools console.

Use console.dir(object) to display an interactive list of the properties of the specified JavaScript object.

var obj = {
    prop1: 'prop1Value',
    prop2: 'prop2Value',
    child: {
      childProp1: 'childProp1Value',
    },
  }
  console.dir(obj) 

Use console.table(object), This function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns.

console.table(obj)  

Do comment if you have any doubts or suggestions on this JS Console log 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