Skip to content

for...in: loop over object keys safely (ES1, ES2020 order)

  • Which keys for...in visits, 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...in is 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() or for...of instead.

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.

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.

// Fragment: syntax
for (const key in expression) statement
for (let key in expression) statement
for (key in expression) statement // assigns to an existing variable or property
  • Which keys: string-keyed properties whose [[Enumerable]] attribute is true, 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 as Object.prototype.toString are 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.
  • null and undefined: the body does not run at all; there is no TypeError. Primitives are boxed, so a string enumerates its index keys '0', '1' and so on.
  • let and const: each iteration gets a fresh binding, so closures created in the body capture that iteration’s key.

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' ]
const lines = ['A-100', 'B-200', 'C-300'];
lines.discount = 0.1; // an extra property on the array
Array.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 0
index 2
value 1
value undefined
value 3

Indexes 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.

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.hasOwn
const unsafe = [];
for (const key in saved) unsafe.push(key);
console.log(unsafe); // the polluted key leaks into a bare for...in
delete 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.

  • Iterating arrays with for...in. You get string indexes, extra properties, inherited methods and no holes. Use for...of, forEach or a classic for loop.
  • 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 with Number(i) or use entries().
  • 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...in on Map or Set. They store entries internally, not as properties, so the loop finds nothing. Use for...of.
  • Writing for (var i = 0 in obj). Annex B still allows this initializer in sloppy-mode scripts for web compatibility, but it is a SyntaxError in strict mode and modules.
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().

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.

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.

  • for...in visits 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 prefer Object.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.