How Many Ways to Iterate Over an Object?

Akash ThoriyaAkash Thoriya
2 min read

Expert-Level Explanation

In JavaScript, there are several ways to iterate over the properties of an object. These include:

  1. for...in loop: Iterates over all enumerable properties of an object.

  2. Object.keys(): Creates an array of an object's own enumerable property names and then iterates using array methods.

  3. Object.values(): Similar toObject.keys(), but creates an array of values.

  4. Object.entries(): Provides an array of[key, value] pairs and can be used with array iteration methods.

  5. forEach with Object.keys/values/entries: UseforEach to iterate over the array returned by these methods.

  6. for...of with Object.keys/values/entries: Requires a conversion to an array format, then iterates over elements.

Creative Explanation

Think of iterating over an object like exploring a house.

  1. for...in loop: walking through every room and noting details (properties).

  2. Object.keys(): Making a list of room names and then visiting each.

  3. Object.values(): listing what's in each room and then checking each item.

  4. Object.entries(): Creating pairs of room names and contents, then reviewing each pair.

  5. forEach with Object.keys/values/entries: Similar to above, but like following a tour guide who points out each item.

  6. for...of with Object.keys/values/entries: turning the house exploration into a linear path and walking through it.

Practical Explanation with Code

const person = { name: 'Alice', age: 30 };

// for...in Loop
for (const key in person) {
    console.log(key, person[key]);
}

// Object.keys()
Object.keys(person).forEach(key => console.log(key, person[key]));

// Object.values()
Object.values(person).forEach(value => console.log(value));

// Object.entries()
for (const [key, value] of Object.entries(person)) {
    console.log(key, value);
}

Real-world Example

Iterating over an object in different ways is like conducting an inventory check in a store. Each method is a different approach to reviewing what items (properties) are in stock and their details (values).

0
Subscribe to my newsletter

Read articles from Akash Thoriya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Akash Thoriya
Akash Thoriya

As a senior full-stack developer, I am passionate about creating efficient and scalable web applications that enhance the user experience. My expertise in React, Redux, NodeJS, and Laravel has enabled me to lead cross-functional teams and deliver projects that consistently exceed client expectations.