Code highlights logo

Learn

Objects

Looping Through Objects (for…in)

Looping through objects can be extremely useful when you want to perform a specific operation on each property within an object. The for...in loop provides a convenient way to achieve this.

Syntax

The syntax for the for...in loop is as follows:

1for (var key in object) {
2 // code to be executed
3}

Iterating through Object Properties

By using the for...in loop, we can iterate over each property in an object and perform actions or access their values.

Let's consider an example where we have an object called person:

1var person = {
2 name: 'John',
3 age: 30,
4 profession: 'Developer'
5};

We can loop through the properties of this object using the for...in loop:

1for (var key in person) {
2 console.log(key + ': ' + person[key]);
3}

The above code will output:

1name: John
2age: 30
3profession: Developer

Instructions

1.

Use a for...in loop to iterate through the person object:

  • Inside the loop, assign each key to the key variable.
  • Use console.log to print the value of each key in the following format: <key>: <value>.

EXPECTED OUTPUT:

1name: John
2age: 30
3profession: Engineer
4hobbies: reading,painting,coding

Sign up to start coding

Already have an account?

Sign In

Course content