Skip to content
Tutorials Center
My learning

Topics

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().

JavaScript
for (const key in object) {
  console.log(key, object[key]);
}

Try it

JS Keys of an object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Inherited properties and arrays

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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 with Object.keys() and Object.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), but for...of gives characters.
  • const is fine in the header because each iteration creates a new binding.
  • break, continue and 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.