Iterate Property Names
JavaScript for..in
`for..in` walks the **keys** of an object. Useful, but easy to confuse with `for..of`. Know the difference.
What you'll learn
- Iterate an object's property names with `for..in`
- Know why `for..in` is the wrong choice for arrays
- Prefer `Object.keys/values/entries` for cleaner code
for..in iterates the property names (keys) of an object. The
shape:
for (const key in object) {
// ...
}
const user = { name: "Ada", age: 36, role: "admin" };
for (const key in user) {
console.log(`${key}: ${user[key]}`);
}
// "name: Ada"
// "age: 36"
// "role: admin" ▶ Preview: console
for..in vs for..of
This is the most common confusion in JavaScript loops.
| Loop | Iterates over | Use for |
|---|---|---|
for..in | KEYS (strings) | Object properties |
for..of | VALUES | Arrays, strings, sets, maps, iterables |
const colors = ["red", "green", "blue"];
for (const x of colors) console.log(x); // "red", "green", "blue" ← values
for (const x in colors) console.log(x); // "0", "1", "2" ← indices (as strings) ▶ Preview: console
Prefer Object.keys/values/entries
Modern JavaScript usually reaches for Object.keys/values/entries
instead of for..in. They return plain arrays, which you can
iterate with for..of or array methods.
const user = { name: "Ada", age: 36 };
for (const key of Object.keys(user)) {
console.log(key);
}
// "name", "age"
for (const value of Object.values(user)) {
console.log(value);
}
// "Ada", 36
for (const [key, value] of Object.entries(user)) {
console.log(`${key} = ${value}`);
}
// "name = Ada"
// "age = 36" ▶ Preview: console
These are explicit, work with map/filter/reduce, and don’t pull
in inherited properties.
When for..in Is Right
for..in is appropriate when:
- You’re iterating an object’s properties.
- You’re OK including inherited enumerable properties (rare).
For everything array- or collection-shaped, for..of (or
forEach/map/filter) is the right choice.
Up Next
A loop driven by a condition, not a counter — while.