How to Display an Object in JavaScript

To display an object in JavaScript, you can use the “console.log()” method to output the object to the console.

Example

const obj = {
  name: "Niva",
  age: 30,
  city: "Mumbai"
};

console.log(obj);

Output

{ name: 'Niva', age: 25, city: 'Mumbai' }

Alternatively, you can convert the object to a string using JSON.stringify() method and then display it on the webpage.

const obj = {
  name: "Niva",
  age: 25,
  city: "Mumbai"
};

const objStr = JSON.stringify(obj);

document.getElementById("demo").innerHTML = objStr;

In this code example, the JSON.stringify() method converts the object to a JSON string, which is then assigned to the objStr variable. The innerHTML property of an HTML element with the ID “demo” is then set to the objStr variable, which displays the object as a string on the webpage.

Leave a Comment