How to Display a JavaScript Object

In this snippet, you will find fast-solutions on how to display an object in JavaScript.

For example, when you need to print the object for some debugging purposes, you can use the following code:

let object = {
  prop1: 'prop1Value',
  prop2: 'prop2Value',
  child: {
    childProp1: 'childPropValue1'
  }
}
console.log(object);

Please, notice that you only need to log the object. The following code will not work in this case:

let object = new Object("W3Docs");
console.log('My object :   ' +  object)

Also, take into consideration that a comma may be used in the log method. The initial line of the output will be the string, and only then the object can be rendered. Here is an example:

let object = new Object("W3Docs");
console.log('My object:   ',   object);

There is also an alternative method: it’s the native JSON.stringify() method. It operates with nested objects, and all the major browsers support it.

Here is an example of using the JSON.stringify() method:

let object = new Object("W3Docs");
str = JSON.stringify(object);
str = JSON.stringify(object, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()
str = JSON.stringify(object);

You can apply the custom JSON.stringify replacer, in case the following JavaScript error occurs:

"Uncaught TypeError: Converting circular structure to JSON"

Describing the JSON.stringify() Method

The JSON.stringify() method is targeted at converting JavaScript objects into strings. The data should be a string at the time of sending it to a web server. It accepts the following parameters: value, replacer, space. The value is the one that needs to be converted into a JSON. The replacer is considered an optional parameter. It can be an altering function, either an array used as a selected filter for the stringify. In case the value is empty or null, all the properties of the object included in a string. Space is an optional parameter, as well. It is used for controlling spacing inside the final string created using the JSON.stringify() method. The return value returns a string for a particular value.

The Usage of JavaScript Objects

Objects are the most important data-type, forming the building block for modern JavaScript. They are different from primitive data types in the sense that when the primitives store a single value each, objects are more complicated and may contain any combination of primitives, as well as reference data types.

An object itself is related to reference data types.

Objects may be created using figure brackets {…} with an optional list of properties.


Do you find this helpful?

Related articles