JavaScript Reference ยท Statements and Declarations
The for...in statement
Reference for the JavaScript for...in statement: looping over enumerable string keys, inherited properties, key order, arrays and better alternatives.
The for...in statement loops over the enumerable string-keyed property names of an object, including enumerable properties it inherits through the prototype chain. On each pass the variable holds the key as a string. Symbol keys are skipped.
It is meant for plain objects used as dictionaries. For arrays and other iterables use for...of, and for own keys only use Object.keys(), Object.values() or Object.entries().
for (const key in object) { console.log(key, object[key]); }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
for (variable in object) { statement }
| Part | Description |
|---|---|
variable |
A binding (const, let or var) or an assignment target that receives each key as a string. |
object |
An expression. If it is null or undefined the loop simply does not run; primitives are wrapped in objects. |
Usage notes
- Order. Integer-like keys come first in ascending numeric order, then other string keys in creation order. Modern engines follow this for ordinary objects.
- Inherited keys. Enumerable properties on the prototype chain are included. Filter with
Object.hasOwn(obj, key), or avoid the problem withObject.keys()andObject.entries(). - Adding and deleting while looping. Deleting a property that has not been visited yet means it is not visited. Properties added during the loop may or may not be visited; do not rely on it.
- Arrays. It yields indexes as strings, will include extra enumerable properties and inherited ones, and is slower than index loops. Avoid it for arrays.
- Strings can be iterated with
for...in(indexes), butfor...ofgives characters. constis fine in the header because each iteration creates a new binding.break,continueand labels work as in other loops.- Non-enumerable properties such as built-in methods are not visited, which is why
for (k in {})is empty even though objects have methods.
Browser support
Supported in every JavaScript engine.
Related
for...of,for- Lessons: for...of and for...in, Objects, Prototypes