The for...in Loop

Loop over the keys of an object.

Syntaxfor (const key in object) { ... }

The for...in loop iterates over the keys (property names) of an object. Use the key to read each value.

Objects vs arrays

Use for...in for objects and for...of for array values. Using for...in on arrays gives you index strings, which is rarely what you want.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Enumerate all keys of a settings object to render each setting row in an admin panel.
  • Inspect an unknown API response object to log all its properties for debugging.
  • Copy only own enumerable properties from one object to another in a custom assign utility.

More examples

Loop over object keys

Iterates over each enumerable key of the settings object and logs its value.

Example · js
const settings = { theme: "dark", lang: "en", fontSize: 14 };
for (const key in settings) {
  console.log(key + ": " + settings[key]);
}

Guard with hasOwn to skip inherited

Uses Object.hasOwn inside for-in to skip inherited properties and process only own keys.

Example · js
const base = { inherited: true };
const child = Object.create(base);
child.own = 42;
for (const key in child) {
  if (Object.hasOwn(child, key)) console.log(key); // "own" only
}

Build key list from object

Collects all enumerable key names of an object into an array using for-in.

Example · js
const user = { id: 1, name: "Alice", role: "admin" };
const keys = [];
for (const k in user) keys.push(k);
console.log(keys); // ["id", "name", "role"]

Discussion

  • Be the first to comment on this lesson.
The for...in Loop — JavaScript | SoundsCode