for...in

Walks the names of an object’s enumerable properties, including ones inherited from the prototype.

On this page

Example

#
JavaScript
const student = { name: 'Emma', level: 3, course: 'JavaScript' }

for (const key in student) {
  console.log(`${key}: ${student[key]}`)
}
Console
name: Emma
level: 3
course: JavaScript

Definition and usage

#

On every turn, a for...in loop hands you the next key of an object, as a string. You read the value through square brackets: object[key]. It’s the oldest way to walk the properties of a plain object.

The loop also covers enumerable properties inherited from the prototype. In ordinary object literals that rarely gets in the way, but for objects created with Object.create() extra keys show up. You can filter them out with the condition Object.hasOwn(object, key).

for...in doesn’t suit arrays: it returns indexes as strings ("0", "1") and may pick up extra properties. Modern code more often uses Object.keys() or Object.entries() together with for...of, since they return only an object’s own keys.

Syntax

#
Syntax
for (const key in object) {
  // statements
}

More examples

#
Inherited keys and Object.hasOwn()
JavaScript
const defaults = { theme: 'dark' }
const settings = Object.create(defaults)
settings.sounds = true

for (const key in settings) {
  console.log(key, Object.hasOwn(settings, key))
}
Console
sounds true
theme false
Pitfall: for...in on an array
JavaScript
const points = [10, 20, 30]

for (const index in points) {
  console.log(index + 1)
}
Console
01
11
21

The indexes are strings, so + 1 concatenates text instead of adding. For arrays, use for...of or forEach().

Key order
JavaScript
const lessons = { b: 'CSS', 2: 'Loops', a: 'HTML', 1: 'Variables' }

for (const key in lessons) {
  console.log(key)
}
Console
1
2
b
a

Keys that look like integers come first, in ascending order. The rest keep the order in which they were added.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • If you only need an object’s own keys, it’s simpler to write for (const key of Object.keys(obj)). You don’t need Object.hasOwn() then.
  • Don’t add or remove properties while a for...in loop is running. There’s no guarantee whether new keys get visited.
  • Symbol keys and non-enumerable properties are skipped.

Related entries

#

Spotted a mistake or missing an example? Write to us.