Lesson

JS Loop For In

10 min reading
Free Course

JavaScript for...in: Enumerating Object Properties Safely

The JavaScript for...in loop iterates over the enumerable string keys of an object, including inherited keys on its prototype chain. It is built for inspecting plain objects, not arrays.

How for...in Differs from for...of

Many beginners mix up for...in and for...of. Remember this simple rule: for...in iterates over keys (property names), while for...of iterates over values in arrays, strings, Maps, and Sets.

Because for...in also visits enumerable properties inherited from prototypes, older code always wrapped the body with Object.hasOwn(obj, key) (or hasOwnProperty) to skip inherited keys.

Modern Alternative: Object.entries() with for...of

Today, combining Object.keys() or Object.entries() with for...of is cleaner and skips prototype keys automatically.

const userConfig = {
  theme: "dark",
  language: "en",
  notifications: true,
};

// Classic for...in with Object.hasOwn guard
for (const key in userConfig) {
  if (Object.hasOwn(userConfig, key)) {
    console.log(`for..in -> ${key}: ${userConfig[key]}`);
  }
}

// Preferred modern ES6+ approach
for (const [key, value] of Object.entries(userConfig)) {
  console.log(`entries -> ${key}: ${value}`);
}

Common Mistakes to Avoid

  • Using for...in to loop over an array: for...in visits array indexes as strings ("0", "1"), can include custom properties attached to the array, and runs slower than for...of.
  • Expecting integer keys in insertion order: JavaScript sorts non-negative integer keys ("2", "10") numerically before string keys when enumerating objects.
  • Skipping the Object.hasOwn() check: If a third-party library extends a prototype, an unguarded for...in loop pulls in unexpected methods.

Frequently Asked Questions

Does for...in visit Symbol keys?

No, for...in visits enumerable string keys only and ignores Symbol properties. Use Object.getOwnPropertySymbols() if you need symbols.

Can I use const for the loop variable in for...in?

Yes, for (const key in obj) works because each iteration creates a brand-new binding for key. Use const unless you reassign key inside the loop body.

Why is Object.entries(obj) usually preferred over for...in?

Object.entries(obj) returns only the object's own enumerable [key, value] pairs, eliminating prototype bugs and allowing clean array destructuring.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
JavaScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum