How to Display an Object in JavaScript

Here are five different ways to display an Object in JavaScript.

  1. Using console.log()
  2. Using JSON.stringify()
  3. Displaying the Object Properties in a Loop
  4. Displaying the Object Properties based on their properties
  5. Displaying the Object using Object.values()

Method 1: Using console.log()

The easiest way to display an object in JavaScript is to print it to the console “using the console.log() method.”

const person = {
  name: "John",
  age: 30
};

console.log(person); 

Output

{ name: 'John', age: 30 }

Method 2: Using JSON.stringify()

You can convert an object to a JSON-formatted string using JSON.stringify() and then display it. This method is helpful if you want to send the object over a network or save it as a string.

const person = {
  name: "John",
  age: 30
};

console.log(JSON.stringify(person, null, 2));

Output

{
  "name": "John",
  "age": 30
}

Method 3: Displaying the Object Properties in a Loop

You can loop through an object’s properties using a for…in loop or Object.keys() and then display each property.

const person = {
  name: "John",
  age: 30
};

for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}

// or

Object.keys(person).forEach(key => {
  console.log(`${key}: ${person[key]}`);
});

Output

name: John
age: 30

name: John
age: 30

Method 4: Displaying the Object based on their properties

You can display an object based on its properties using the console.log() method.

const person = { name: "John", age: 30 };

console.log(person.name + ", "+ person.age);

Output

John, 30

Method 5: Displaying the Object using Object.values()

You can convert any JavaScript object to an array using the Object.values() method.

const person = { name: "John", age: 30 };

vals = Object.values(person)

console.log(vals)

Output

[ 'John', 30 ]

Conclusion

From a pure performance standpoint:

  1. The console.log() method can be slow for huge objects.
  2. JSON.stringify() can also be slow for large complex objects but generally efficient for smaller ones.

The “best” method for displaying objects in JavaScript largely depends on the context in which you must display them.

Related posts

JavaScript Object length

Object to String in JavaScript

Array to Object in JavaScript

String to Object in JavaScript