for...in: loop over object keys safely (ES1, ES2020 order)
What you’ll learn
Section titled “What you’ll learn”- Which keys
for...invisits, in what order, and why inherited properties show up. - How to guard the loop with
Object.hasOwn()so prototype pollution cannot leak into your data. - Why
for...inis the wrong loop for arrays and strings. - What happens when you add or delete properties during the loop.
- When to choose
Object.keys(),Object.entries()orfor...ofinstead.
Summary
Section titled “Summary”TL;DR: for (const key in obj) runs the body once for every enumerable, string-keyed property of obj and of its prototype chain. Keys are always strings; symbols are skipped. It is the oldest loop over objects in the language, present since the first edition (ECMAScript 1, 1997). ECMAScript 2020 pinned down the enumeration order for ordinary objects.
Use it when you deliberately want inherited keys, or guard it with Object.hasOwn(). For most code, Object.keys() or Object.entries() with for...of is clearer.
The problem it solves
Section titled “The problem it solves”Plain objects are JavaScript’s dictionaries, and you often need to walk keys you do not know in advance: copying settings, diffing configurations, serializing filters. Before ES5 added Object.keys() (2009), for...in was the only way.
Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). The outputs shown were produced with Node.js 22.23.
// OrdersPortal: user settings inherit from shared defaults.const defaults = { currency: 'USD', pageSize: 20 };const settings = Object.create(defaults);settings.pageSize = 50;settings.theme = 'dark';settings[2] = 'second';settings[1] = 'first';settings[Symbol('internal')] = true;Object.defineProperty(settings, 'secret', { value: 'x', enumerable: false });
for (const key in settings) { console.log(key, '->', settings[key], Object.hasOwn(settings, key) ? '(own)' : '(inherited)');}console.log(Object.keys(settings));Output:
1 -> first (own)2 -> second (own)pageSize -> 50 (own)theme -> dark (own)currency -> USD (inherited)[ '1', '2', 'pageSize', 'theme' ]That one loop shows almost every rule: integer-like keys first in ascending order, then string keys in insertion order, then the prototype’s keys; the shadowed pageSize on the prototype is not repeated; the symbol key and the non-enumerable secret are skipped. Object.keys() returns the same own keys without the inherited currency.
How it works
Section titled “How it works”// Fragment: syntaxfor (const key in expression) statementfor (let key in expression) statementfor (key in expression) statement // assigns to an existing variable or property- Which keys: string-keyed properties whose
[[Enumerable]]attribute istrue, on the object and then on each prototype up the chain. Symbol keys are never visited. Properties created by assignment or object literals are enumerable; built-in methods such asObject.prototype.toStringare not, which is why they do not appear. - Key type: the loop variable is always a string, even for array indexes.
- Shadowing: a prototype key is skipped if a key with the same name was already processed lower in the chain, even if that lower property is non-enumerable.
- Order: for ordinary objects, the spec (since ES2020, the for-in mechanics proposal) requires the order of
Object.keys()for each object: integer-like keys ascending, then other strings in creation order, then the prototype’s keys. Proxies, typed arrays, module namespace objects and host objects are exempt, and the order is also unspecified once you add or delete properties mid-loop or change the prototype. nullandundefined: the body does not run at all; there is noTypeError. Primitives are boxed, so a string enumerates its index keys'0','1'and so on.letandconst: each iteration gets a fresh binding, so closures created in the body capture that iteration’s key.
Mutation during the loop
Section titled “Mutation during the loop”The spec says a property deleted before it is reached is not visited, and a property added during the loop may or may not be visited. Never rely on either:
const order = { b: 1, a: 2 };for (const k in order) { if (k === 'b') { delete order.a; order.c = 3; } console.log(k);}console.log(Object.keys(order));Output (Node.js 22; c is not guaranteed to be skipped in other engines):
b[ 'b', 'c' ]Arrays are the classic trap
Section titled “Arrays are the classic trap”const lines = ['A-100', 'B-200', 'C-300'];lines.discount = 0.1; // an extra property on the arrayArray.prototype.last = function () { return this[this.length - 1]; }; // an old-style polyfill
const seen = [];for (const i in lines) seen.push(`${i}:${typeof i}`);console.log(seen);delete Array.prototype.last;
const sparse = [1, , 3];for (const i in sparse) console.log('index', i);for (const v of sparse) console.log('value', v);Output:
[ '0:string', '1:string', '2:string', 'discount:string', 'last:string']index 0index 2value 1value undefinedvalue 3Indexes arrive as strings (i + 1 would be '01'), extra properties and polluted prototype methods leak in, and holes are skipped. for...of visits values, including holes as undefined, and nothing else.
Realistic example
Section titled “Realistic example”OrdersPortal stores user settings as JSON and needs to send only the settings that differ from the defaults. A bare for...in would pick up anything a third-party script added to Object.prototype; the Object.hasOwn() guard keeps the result correct.
function changedSettings(current, defaults) { const changes = {}; for (const key in current) { if (!Object.hasOwn(current, key)) continue; // skip inherited keys if (current[key] !== defaults[key]) changes[key] = current[key]; } return changes;}
const defaults = { currency: 'USD', pageSize: 20, showArchived: false };const saved = JSON.parse('{"currency":"EUR","pageSize":20,"showArchived":true}');
console.log(changedSettings(saved, defaults));
// A library somewhere pollutes Object.prototype:Object.prototype.debugMode = true;console.log(changedSettings(saved, defaults)); // still correct thanks to Object.hasOwnconst unsafe = [];for (const key in saved) unsafe.push(key);console.log(unsafe); // the polluted key leaks into a bare for...indelete Object.prototype.debugMode;Output:
{ currency: 'EUR', showArchived: true }{ currency: 'EUR', showArchived: true }[ 'currency', 'pageSize', 'showArchived', 'debugMode' ]Object.hasOwn() (ES2022) replaces the older Object.prototype.hasOwnProperty.call(obj, key) idiom and also works on objects created with Object.create(null), which have no hasOwnProperty method. The same function written as for (const [key, value] of Object.entries(current)) needs no guard at all, because Object.entries() returns own keys only.
Common mistakes
Section titled “Common mistakes”- Iterating arrays with
for...in. You get string indexes, extra properties, inherited methods and no holes. Usefor...of,forEachor a classicforloop. - Forgetting inherited keys. Without
Object.hasOwn(), keys from the prototype chain, including polluted ones, enter your logic. - Expecting symbols or non-enumerable properties. Use
Reflect.ownKeys()when you need every own key, including symbols and non-enumerable ones. - Treating the key as a number.
for (const i in arr) total += arr[i + 1]concatenates strings. Convert withNumber(i)or useentries(). - Mutating the object you are walking. Adding keys mid-loop has unspecified results. Collect changes first, or loop over a snapshot from
Object.keys(). - Using
for...inonMaporSet. They store entries internally, not as properties, so the loop finds nothing. Usefor...of. - Writing
for (var i = 0 in obj). Annex B still allows this initializer in sloppy-mode scripts for web compatibility, but it is aSyntaxErrorin strict mode and modules.
When to use it and when not to
Section titled “When to use it and when not to”| Need | Use |
|---|---|
| Own enumerable keys of a plain object | Object.keys(obj) |
| Own keys and values together | for (const [k, v] of Object.entries(obj)) |
| Keys including inherited enumerable ones (prototype-based defaults) | for...in |
| Every own key, including symbols and non-enumerable | Reflect.ownKeys(obj) |
Array, string, Map, Set or generator values |
for...of |
| Data from an async source | for await...of |
for...in still earns its place when inheritance is the point, for example a debugging helper that shows effective settings including defaults inherited through Object.create().
Compatibility
Section titled “Compatibility”for...in has been in every JavaScript engine since the beginning: MDN’s compatibility data lists Chrome 1, Edge 12, Firefox 1, Safari 1, Internet Explorer 3, Node.js 0.10, Deno 1.0 and Bun 1.0. The ES2020 ordering rules codified what engines already did for ordinary objects; older engines may differ on the exotic cases the spec still leaves open. Object.hasOwn(), used in the guard, needs Node.js 16.9 or a current browser; fall back to Object.prototype.hasOwnProperty.call() on older targets.
Interview questions
Section titled “Interview questions”1. What is the difference between for...in and for...of?
for...in walks enumerable string keys of any object, including inherited ones, and gives you keys as strings. for...of uses the iterator protocol (Symbol.iterator) and gives you values from iterables such as arrays, strings, Map and Set; plain objects are not iterable, so it throws a TypeError on them.
2. Is the order of for...in guaranteed?
Since ES2020, yes for ordinary objects that are not changed during the loop: integer-like keys ascending, then string keys in insertion order, then each prototype’s keys in the same way, skipping shadowed names. It is still unspecified for proxies, typed arrays, module namespaces and host objects, and when properties or prototypes change mid-loop.
3. Why does Object.hasOwn() matter inside for...in?
Because the loop includes inherited enumerable keys. If any code has added an enumerable property to Object.prototype or to a custom prototype, it appears in every unguarded loop. Object.hasOwn(obj, key) filters to own properties and, unlike obj.hasOwnProperty(key), works on null-prototype objects and cannot be shadowed by a property named hasOwnProperty.
4. Senior scenario: a code review finds for...in used throughout a data-mapping layer that handles JSON from an API. What do you recommend?
Replace array loops first, since for...in there is a real bug source (string indexes, extra keys). For JSON objects, Object.entries() with for...of states the intent and needs no guard. Consider Map or Object.create(null) for dictionary data, enable ESLint’s guard-for-in for new code, and keep for...in only where inherited keys are intended, with a comment saying so.
Key takeaways
Section titled “Key takeaways”for...invisits enumerable string keys of an object and its prototype chain; symbols and non-enumerable properties are skipped.- ES2020 fixed the order for ordinary objects: integer keys ascending, then insertion order, then the prototype.
- Guard with
Object.hasOwn(), or preferObject.keys()/Object.entries()for own keys. - Never use it for arrays or other iterables; use
for...of. - Do not add or delete properties while the loop runs.
Related pages
Section titled “Related pages”- for…of: the value loop for arrays, strings,
Map,Setand generators. - Async iteration:
for await...offor asynchronous sources. - Object.keys and Object.entries: own-key alternatives.
- Object.hasOwn: the safe own-property check.
- Prototypes: where inherited keys come from.
- Objects and Control flow: the basics behind this page.
Official references
Section titled “Official references”- ECMAScript Language Specification: The
for-in,for-of, andfor-await-ofStatements (current draft) - ECMAScript specification: EnumerateObjectProperties
- ECMAScript 2020 Language Specification (ECMA-262, 11th edition), the first edition with the for-in order rules
- TC39 proposal: for-in mechanics
- MDN: for…in
- MDN: Enumerability and ownership of properties
- MDN: Object.hasOwn()
- ESLint rule: guard-for-in