Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 46

Iterating Object Properties with for...in and Object.keys()

This lesson is built with resources from youtube.com, dev.to and 1 more site.

Hello and welcome back!

In our previous lesson, we demystified the this keyword, understanding that its value depends on how a function is called. You learned how to predict its behavior in object methods, standalone functions, and arrow functions. This gave you a solid foundation for understanding how objects and their associated functions behave.

Today, we'll build on that by learning how to work with an object's data in bulk. We'll focus on the learning outcome: Iterate over an object's properties using the for...in loop and Object.keys(). Knowing how to loop through an object is a fundamental skill for tasks like displaying data, transforming it, or sending it to a server. This is a crucial step on your path toward Next.js, where you'll constantly work with objects representing component props, page data, and API responses.

Why Do We Need to Iterate Over Objects?

Imagine you have an object representing a user profile.

const user = {
  id: 'usr_12345',
  username: 'dev_learner',
  email: 'learner@example.com',
  isActive: true
};

You might want to display all of this information on a webpage. You could access each property one by one (user.username, user.email, etc.), but what if the object had 50 properties? Or what if you didn't know the exact property names beforehand? This is where iteration comes in. We need a way to programmatically go through each property of the object.

Let's explore the two primary ways to achieve this.


Method 1: The for...in Loop (The Classic Way)

The for...in loop is the original JavaScript construct for iterating over the properties of an object. It loops through the keys (property names) of the object.

The basic syntax looks like this:

for (const key in object) {
  // 'key' will be the property name (a string) on each iteration
  // To get the value, we use bracket notation: object[key]
  console.log(`${key}: ${object[key]}`);
}

Applying this to our user object:

const user = {
  username: 'dev_learner',
  email: 'learner@example.com',
  isActive: true
};

for (const propertyName in user) {
  console.log(`${propertyName}: ${user[propertyName]}`);
}

// Console Output:
// username: dev_learner
// email: learner@example.com
// isActive: true

A "Deep Dive" into for...in: The Prototype Chain

You have a preference for understanding the "why," so here's a critical detail about for...in. It doesn't just iterate over the properties you defined directly on the object; it also iterates over inherited properties from its prototype (its "parent" object). This can sometimes lead to unexpected behavior.

To prevent this, it's a best practice to check if the property belongs directly to the object using the hasOwnProperty() method.

The following video explains this concept clearly.

How to loop over objects in JavaScript

The video 'How to loop over objects in JavaScript' from saperis demonstrates the for...in loop and immediately highlights the issue with inherited properties and how to solve it.

Watch from 00:44 to 02:45. Pay close attention to the hasOwnProperty() check. This is the standard way to make a for...in loop safe and predictable.

So, a more robust version of our loop looks like this:

for (const key in user) {
  if (user.hasOwnProperty(key)) {
    console.log(`${key}: ${user[key]}`);
  }
}

This ensures you are only working with the properties that truly belong to your user object.


Method 2: Object.keys() (The Modern Way)

Modern JavaScript provides a cleaner and often safer way to handle object iteration: the Object.keys() method.

Object.keys(yourObject) takes an object as an argument and returns an array containing the names of the object's own properties.

This is powerful for two reasons:

  1. It automatically ignores inherited properties, so you don't need a hasOwnProperty() check.
  2. Since it returns a standard array, you can use any array looping method you know (like forEach from our upcoming array module) or the for...of loop we've seen before.
const user = {
  username: 'dev_learner',
  email: 'learner@example.com',
  isActive: true
};

const keysArray = Object.keys(user);
console.log(keysArray); // Output: ['username', 'email', 'isActive']

// Now we can loop over this array to get the keys
for (const key of keysArray) {
  // And use the key to access the value in the original object
  console.log(`${key}: ${user[key]}`);
}

This approach is generally preferred in modern code because it's more explicit and less prone to errors from the prototype chain.

The next video provides an excellent introduction to this method.

Easy Ways to Loop Over Objects in JavaScript

Let's watch 'Easy Ways to Loop Over Objects in JavaScript' from the dcode channel. This section will introduce Object.keys() and explain its purpose.

Watch from the beginning to 03:11. Focus on understanding what Object.keys() returns (an array of keys) and why this is useful for data transformation.

Test your understanding!

You have an object representing product inventory.

const inventory = {
  apples: 15,
  oranges: 32,
  bananas: 18
};

Your task is to write code that calculates the total number of all fruits in the inventory. Use Object.keys() and a loop to solve this.

Show answer

Here is one way to solve it:

const inventory = {
  apples: 15,
  oranges: 32,
  bananas: 18
};

let totalFruits = 0;
const fruitKeys = Object.keys(inventory); // Get an array: ['apples', 'oranges', 'bananas']

for (const fruit of fruitKeys) {
  // On each loop, 'fruit' is a key like 'apples'
  // inventory[fruit] gets the corresponding value (e.g., 15)
  totalFruits += inventory[fruit];
}

console.log(totalFruits); // Output: 65

Explanation:

  1. Object.keys(inventory) gives us an array of the property names: ['apples', 'oranges', 'bananas'].
  2. We initialize a totalFruits variable to 0.
  3. The for...of loop iterates over our new array of keys.
  4. Inside the loop, inventory[fruit] uses the key from the current iteration to look up the corresponding value in the inventory object.
  5. We add this value to our totalFruits counter.

Beyond Keys: Object.values() and Object.entries()

The Object.keys() method is part of a family of useful Object helper methods. Since you're interested in the deep theory, let's briefly explore two more that are essential for modern JavaScript. They are not part of today's core outcome but are so closely related that learning them now will be a great advantage.

  1. Object.values(obj): Returns an array of the object's own property values.
*This diagram shows how `Object.values()` extracts just the values from an object and places them into an array.*

2. Object.entries(obj): This is perhaps the most useful. It returns an array of [key, value] pairs. It gives you both the key and the value together!

*This image compares `Object.keys()` and `Object.entries()`, showing how `Object.keys()` returns an array of keys, while `Object.entries()` returns an array of key-value pair arrays.*

Let's see how Object.entries() creates a very elegant iteration pattern when combined with a for...of loop and array destructuring (which we will cover in detail later).

Easy Ways to Loop Over Objects in JavaScript

Let's continue with the dcode video. This next part compares the old for...in loop with the modern Object.entries() method, which is a perfect illustration of why the modern approach is often better.

Watch from 04:43 to 09:02. Pay special attention to the side-by-side comparison of the traditional for...in loop and the modern for...of loop using Object.entries(). Notice how Object.entries() eliminates the need for hasOwnProperty and gives you both key and value directly.

As the video showed, using Object.entries() is often the cleanest way to loop over both keys and values:

const user = {
  username: 'dev_learner',
  email: 'learner@example.com'
};

// The for...of loop with destructuring
for (const [key, value] of Object.entries(user)) {
  console.log(`${key}: ${value}`);
}

// Console Output:
// username: dev_learner
// email: learner@example.com

This pattern is extremely common in modern JavaScript, TypeScript, and React/Next.js development.


Summary: Choosing the Right Method

Here is a helpful summary table that compares the techniques we've discussed.

Understanding Object Iteration in JavaScript: `for...of` vs ` ...

This article, 'Understanding Object Iteration in JavaScript', provides a concise comparison table that summarizes when to use each method. It's a great reference.

Scroll down to the table in section '4. Comparison of Object Iteration Techniques'. Review the table to solidify your understanding of the differences between for...in, Object.keys(), Object.values(), and Object.entries().


Conclusion

You've now learned the essential techniques for accessing and processing data within objects. This is a skill you'll use constantly as you start building more complex applications.

Key Takeaways:

  • You can iterate over object properties to dynamically access keys and values.
  • The for...in loop is the classic method that iterates over an object's keys, but you should use hasOwnProperty() to avoid iterating over inherited properties.
  • Object.keys(obj) is the modern approach, returning an array of an object's own keys. This is safer and allows you to use powerful array methods.
  • Object.values(obj) and Object.entries(obj) complete the family, giving you arrays of values or [key, value] pairs, respectively.
  • The for (const [key, value] of Object.entries(obj)) pattern is a powerful and highly readable way to iterate over both keys and values in modern JavaScript.

Next Up

We've now covered creating objects, adding properties and methods, understanding this, and iterating over properties. To complete our deep dive into objects, the next lesson will cover a quick but useful topic: Use ES6 shorthand for defining properties and methods in object literals. This will teach you some modern syntax for making your object creation code more concise and readable.