JavaScript Program to Loop Through an Object

To understand this example, you should have the knowledge of the following JavaScript programming topics:


Example 1: Loop Through Object Using for...in

Output

name - John
age - 20
hobbies - ["reading", "games", "coding"]

In the above example, the for...in loop is used to loop through the student object.

The value of each key is accessed by using student[key].

Note: The for...in loop will also count inherited properties.

For example,

Output

name - John
age - 20
hobbies - ["reading", "games", "coding"]
gender - male

If you want, you can only loop through the object's own property by using the hasOwnProperty() method.

if (student.hasOwnProperty(key)) {
    ++count:
}

Example 2: Loop Through Object Using Object.entries and for...of

Output

name - John
age - 20
hobbies - ["reading", "games", "coding"]

In the above program, the object is looped using the Object.entries() method and the for...of loop.

The Object.entries() method returns an array of a given object's key/value pairs. The for...of loop is used to loop through an array.