How to Iterate Over Object Properties in JavaScript
To iterate over object properties in JavaScript, use
for...in to loop through all enumerable keys, or use Object.keys() or Object.entries() with forEach or for...of for more control. These methods let you access keys and values easily.Syntax
Here are common ways to loop over object properties:
for...in: loops over all enumerable keys.Object.keys(obj).forEach(): loops over keys array.Object.entries(obj).forEach(): loops over [key, value] pairs.
javascript
for (const key in obj) { // use obj[key] } Object.keys(obj).forEach(key => { // use obj[key] }); for (const [key, value] of Object.entries(obj)) { // use key and value }
Example
This example shows how to print each property and its value using different methods.
javascript
const person = { name: 'Alice', age: 30, city: 'Paris' }; console.log('Using for...in:'); for (const key in person) { console.log(key + ': ' + person[key]); } console.log('\nUsing Object.keys().forEach():'); Object.keys(person).forEach(key => { console.log(key + ': ' + person[key]); }); console.log('\nUsing Object.entries() with for...of:'); for (const [key, value] of Object.entries(person)) { console.log(key + ': ' + value); }
Output
Using for...in:
name: Alice
age: 30
city: Paris
Using Object.keys().forEach():
name: Alice
age: 30
city: Paris
Using Object.entries() with for...of:
name: Alice
age: 30
city: Paris
Common Pitfalls
Common mistakes include:
- Using
for...inwithouthasOwnProperty, which can include inherited properties. - Assuming property order is guaranteed (it is mostly insertion order but not always).
- Trying to use
forEachdirectly on objects (it works only on arrays).
javascript
const obj = Object.create({ inherited: 'yes' }); obj.own = 'no'; console.log('Wrong way (includes inherited):'); for (const key in obj) { console.log(key); } console.log('\nRight way (only own properties):'); for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { console.log(key); } }
Output
Wrong way (includes inherited):
inherited
own
Right way (only own properties):
own
Quick Reference
Summary of methods to iterate object properties:
| Method | Description | Use Case |
|---|---|---|
| for...in | Loops over all enumerable keys including inherited | Use with hasOwnProperty to filter own keys |
| Object.keys() | Returns array of own enumerable keys | Use with forEach or for...of to loop keys |
| Object.entries() | Returns array of [key, value] pairs | Use with for...of to access keys and values directly |
Key Takeaways
Use for...in with hasOwnProperty to avoid inherited properties.
Object.keys() and Object.entries() provide arrays for easy looping.
forEach works on arrays, not directly on objects.
Property order is mostly insertion order but not guaranteed.
Choose the method based on whether you need keys only or keys with values.