Write a JavaScript Program to Loop Through an Object

As a JavaScript programmer, you may need to loop through an object to perform various operations like accessing or manipulating its properties.

In this tutorial, we will discuss how to loop through an object in JavaScript.

In JavaScript, objects are a collection of key-value pairs where each key is unique. To loop through an object, we can use the for…in loop, which iterates over each key in the object.

Here is an example code snippet that demonstrates how to loop through an object using the for…in loop:

const myObject = {
  name: "John",
  age: 30,
  city: "New York"
};

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

In the above code, we first define an object myObject with three properties: name, age, and city.

We then use the for…in loop to iterate over each key in the object. Inside the loop, we access the value of each property using the bracket notation myObject[key] and log it to the console along with the property key.

The output of the above code will be:

name: John
age: 30
city: New York

If you want to perform some specific operation on each property of the object, you can do that inside the for…in loop.

For example, let’s say we want to add a prefix “My ” to each property key before logging it to the console:

for (let key in myObject) {
  console.log(`My ${key}: ${myObject[key]}`);
}

The output of the above code will be:

My name: John
My age: 30
My city: New York

In conclusion, the for…in loop is a useful tool for iterating over an object’s properties in JavaScript.