JavaScript for..in

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.

3 min read Level 2/5 #for-in#loops#objects
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) {
  // ...
}
Iterate an object's keys script.js
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.

LoopIterates overUse for
for..inKEYS (strings)Object properties
for..ofVALUESArrays, strings, sets, maps, iterables
The difference script.js
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.

Object.* helpers script.js
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.

JavaScript while →