Introduction
In JavaScript, objects are used to store key-value pairs. Often, you'll need to loop through each key or value in an object — for example, to display user data, update values, or filter based on certain criteria.
JavaScript provides several methods to iterate over objects:
- for...in loop
- Object.keys()
- Object.values()
- Object.entries()
Example 1: Using for...in
loop
The for...in
loop iterates over all enumerable properties of an object.
const user = {
name: "Alice",
age: 30,
city: "New York"
};
for (let key in user) {
console.log(key + ": " + user[key]);
}
Output:
name: Alice age: 30 city: New York
Question: What does key
represent in the loop?
Answer: It represents each property name (i.e., the keys) of the object.
Example 2: Using Object.keys()
Object.keys(obj)
returns an array of the object’s own enumerable property names (keys). You can use this with forEach()
.
const user = {
name: "Alice",
age: 30,
city: "New York"
};
Object.keys(user).forEach(function(key) {
console.log(key + ": " + user[key]);
});
Output:
name: Alice age: 30 city: New York
This approach is clean and more functional compared to for...in
.
Example 3: Using Object.values()
Object.values(obj)
returns an array of the object’s values.
const user = {
name: "Alice",
age: 30,
city: "New York"
};
Object.values(user).forEach(function(value) {
console.log(value);
});
Output:
Alice 30 New York
Question: When should you use Object.values()
?
Answer: When you are only interested in the values and not the keys.
Example 4: Using Object.entries()
Object.entries(obj)
returns an array of key-value pairs in the format [key, value]
.
const user = {
name: "Alice",
age: 30,
city: "New York"
};
Object.entries(user).forEach(function([key, value]) {
console.log(key + " => " + value);
});
Output:
name => Alice age => 30 city => New York
This is the most powerful method when you need both keys and values together in a clean, iterable format.
Comparison Table
Method | Returns | Best Use Case |
---|---|---|
for...in | Each key (including inherited enumerable) | Simple loops over keys |
Object.keys() | Array of own keys | Working only with own keys |
Object.values() | Array of values | Only values needed |
Object.entries() | Array of [key, value] pairs | Need both keys and values |
Conclusion
JavaScript offers multiple ways to iterate over object properties. The right method depends on whether you need keys, values, or both. Using modern methods like Object.entries()
makes your code cleaner and more readable, especially when working with real-world data.