How to display the content of a JavaScript object in a string format?

I want to display the content of a JavaScript object in a string format, similar to how we use alert() for variables.

How can I JavaScript print object in this formatted way?

The simplest way to convert an object to a readable string format is to use JSON.stringify(). This will convert the object into a JSON string, making it easy to display.

var obj = { name: 'John', age: 30, city: 'New York' };
alert(JSON.stringify(obj));

This method is perfect for displaying the entire object as a string in a readable format. If the object has nested objects or arrays, JSON.stringify() will handle them as well.

If you are in a development or debugging environment, console.log() is the easiest way to display the object directly in the console. This is more useful for complex objects, as console.log() allows you to expand and view nested objects in the browser’s developer tools.

var obj = { name: 'John', age: 30, city: 'New York' };
console.log(obj);

This is particularly helpful for development since you can interact with the logged object directly in your browser’s console, making it more dynamic and easier to inspect.

If you need to display the object’s content in a custom string format (like a key-value pair), you can manually iterate through the object’s keys and concatenate them into a string.

var obj = { name: 'John', age: 30, city: 'New York' };
var result = '';
for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    result += key + ': ' + obj[key] + '\n';
  }
}
alert(result);

This method is useful if you want to customize how the object’s content is displayed, perhaps formatting each key-value pair differently or adding extra details.