The JavaScript for...in statement
The for...in loop iterates over the enumerable keys of an object. for (const key in obj) { ... } gives each property name. It's meant for objects, not arrays — for arrays use for...of. It also walks inherited keys, which is why Object.keys() is often preferred.
Overview
for...in loops over an object's property keys. for (const key in user) gives you each property name as a string, and you read the value with user[key]. It's the old-school way to walk an object's own properties.
Two important caveats keep it out of favor for everyday use. First, it iterates inherited enumerable properties too, not just the object's own — so on objects with a prototype chain you can get keys you didn't expect. The classic guard is if (Object.hasOwn(obj, key)) inside the loop. Second, it's the wrong tool for arrays: it iterates index keys as strings and can include extra enumerable properties, with no guaranteed order. Use for...of for array values.
Because of those gotchas, most modern code skips for...in in favor of Object.keys(), Object.values() or Object.entries(), which return only own properties as a clean array you can loop with for...of or forEach(). Reach for for...in only when you specifically want the full enumerable key set including inherited ones.
Syntax
for (const key in object) {
if (Object.hasOwn(object, key)) {
const value = object[key];
}
}
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const car = { make: 'Toyota', model: 'Corolla', year: 2024 };
const lines = [];
for (const key in car) {
lines.push(key + ': ' + car[key]);
}
document.getElementById('out').textContent = lines.join('\n');
</script>
Best practices
- Use it for objects, never for arrays — for array values use for...of.
- Guard with
Object.hasOwn(obj, key)to skip inherited properties. - Prefer Object.keys()/entries() for own properties in a predictable order.
- Don't rely on a particular iteration order, especially with mixed key types.
Frequently asked questions
What does for...in loop over?
Why shouldn't I use for...in on arrays?
What is the difference between for...in and for...of?
for...in gives object keys; for...of gives iterable values. Keys vs values.