Displaying Objects in JavaScript

Welcome to the world of displaying objects in JavaScript! Objects are fundamental data structures used to store collections of key-value pairs. This chapter delves into various techniques for visualizing these objects, empowering you to effectively present their content.

Basic Display Methods

Using console.log()

  • The most common approach is to use the console.log() function to display an object. However, this might not provide the most readable output, especially for nested objects.
				
					const person = {
  firstName: "Alice",
  lastName: "Smith",
  age: 30
};

console.log(person);

				
			
				
					

{ firstName: "Alice", lastName: "Smith", age: 30 }

				
			

Explanation:

  • We define an object named person with three properties: firstName, lastName, and age.
  • console.log(person) simply prints the entire object to the console. The output might not be very user-friendly for nested objects, but it displays all key-value pairs within curly braces {}.

Accessing and Displaying Properties

  • You can access individual object properties using their keys (property names) enclosed in square brackets [] or dot notation .. Then, you can display the values using console.log().
				
					const person = {
  firstName: "Alice",
  lastName: "Smith",
age: 30
};

console.log("First Name:", person.firstName);  // Accessing using dot notation
console.log("Age:", person["age"]);            // Accessing using square brackets

				
			
				
					

First Name: Alice
Age: 30
				
			

Explanation:

  • We again define the person object.
  • console.log("First Name:", person.firstName) retrieves the value of the firstName property using dot notation (person.) and prints it with a label.
  • console.log("Age:", person["age"]) achieves the same result using square brackets ([]). Square brackets are useful when the property name contains spaces or special characters.

Looping Through Objects

for...in Loop

  • The for...in loop iterates over all enumerable properties of an object, including inherited properties. It provides the property key (name) at each iteration.
				
					const person = {
  firstName: "Alice",
  lastName: "Smith",
  age: 30
};

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

				
			
				
					

firstName: Alice
lastName: Smith
age: 30
				
			

Explanation:

  • The for...in loop iterates through all enumerable properties (properties that can be looped through) in the person object.
  • const key in person defines a variable key that takes on the name (key) of each property at each iteration.
  • Inside the loop, we construct a string using key + ": " + person[key]. This combines the property name with a colon, a space, and then accesses the corresponding value using person[key]. The final string is logged to the console

Object.keys() Method

  • The Object.keys() method returns an array containing the names (keys) of an object’s own enumerable properties. You can then use a for...of loop to iterate through the keys and access corresponding values.
				
					const person = {
  firstName: "Alice",
  lastName: "Smith",
  age: 30
};

const keys = Object.keys(person);

for (const key of keys) {
  console.log(key + ": " + person[key]);
}

				
			
				
					

firstName: Alice
lastName: Smith
age: 30
				
			

Explanation:

  • Here, we use the Object.keys() method to create an array named keys containing only the names (keys) of the enumerable properties in person.
  • The for...of loop iterates through the keys array.
  • Inside the loop, similar to the previous example, we construct and print a string combining the key name with its corresponding value.

Advanced Display Techniques

Stringify with JSON.stringify()

  • The JSON.stringify() method converts an object into a JSON (JavaScript Object Notation) string representation. This can be useful for displaying complex objects in a more structured format, especially when working with data exchange or APIs.
				
					const person = {
  firstName: "Alice",
  lastName: "Smith",
  age: 30,
  hobbies: ["reading", "hiking"]
};

const jsonString = JSON.stringify(person);
console.log(jsonString);

				
			
				
					

{"firstName":"Alice","lastName":"Smith","age":30,"hobbies":["reading","hiking"]}

				
			

Explanation:

  • We create a person object with an additional property hobbies (an array).
  • JSON.stringify(person) converts the entire person object into a JSON string representation stored in the jsonString variable. JSON is a common format for data exchange, and this method provides a structured way to represent the object.

Template Literals

Template literals (backticks “) allow you to embed expressions within strings. This can be helpful for creating formatted output that includes both object properties and descriptive text.

				
					const person = {
  firstName: "Alice",
  lastName: "Smith",
  age: 30
};

console.log(`Full Name: ${person.firstName} ${person.lastName}`);
console.log(`Age: ${person.age}`);

				
			
				
					

Full Name: Alice Smith
Age: 30

				
			

Explanation:

  • Template literals (backticks ) allow you to embed expressions (code) directly within strings. Here, we use them to create more readable output.
  • console.log(Full Name: ${person.firstName} ${person.lastName}); constructs a string. The ${person.firstName} part is an expression that evaluates to the value of the firstName property and gets inserted into the string. Similarly, ${person.lastName} inserts the lastName value.
  • console.log(Age: ${person.age}); follows the same principle to display the age property value with a label.

By mastering these methods, you can effectively display objects in JavaScript, making their content clear and informative for debugging, data visualization, or user interaction. The choice of technique depends on your specific needs and the complexity of the object you're working with. Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India