for...in: Enumerating Object Properties SafelyThe 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.
for...in Differs from for...ofMany 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.
Object.entries() with for...ofToday, 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}`);
}
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."2", "10") numerically before string keys when enumerating objects.Object.hasOwn() check: If a third-party library extends a prototype, an unguarded for...in loop pulls in unexpected methods.for...in visit Symbol keys?No, for...in visits enumerable string keys only and ignores Symbol properties. Use Object.getOwnPropertySymbols() if you need symbols.
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.
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.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.