The Ultimate Guide to Looping Through Objects in JavaScript

Learn to Master One of the Fundamental Skills for Any JavaScript Developer

Max N
3 min readMar 17, 2024

When working with objects in JavaScript, there will inevitably come a time when you need to loop through their properties and values. Whether you’re iterating over an object to perform some operation on each of its properties or simply trying to access its contents, understanding how to loop through objects is a crucial skill for any JavaScript developer.

Let’s dive in and explore the various methods available to accomplish this task.

1. The for...in Loop

The for...in loop is one of the most commonly used techniques for iterating over the properties of an object. Here's how it works:

const person = {
name: 'John Doe',
age: 30,
occupation: 'Software Engineer'
};

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

// Output:
// name: John Doe
// age: 30
// occupation: Software Engineer

In this example, the for...in loop iterates over each key in the person object, and we log both the key and its corresponding value to the console.

2. Object.keys() and Array.prototype.forEach()

--

--

Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.