for. . . in
Walks the names of an object’s enumerable properties, including ones inherited from the prototype.
Example
#const student = { name: 'Emma', level: 3, course: 'JavaScript' }
for (const key in student) {
console.log(`${key}: ${student[key]}`)
}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
#for (const key in object) {
// statements
}More examples
#const defaults = { theme: 'dark' }
const settings = Object.create(defaults)
settings.sounds = true
for (const key in settings) {
console.log(key, Object.hasOwn(settings, key))
}const points = [10, 20, 30]
for (const index in points) {
console.log(index + 1)
}The indexes are strings, so + 1 concatenates text instead of adding. For arrays, use for...of or forEach().
const lessons = { b: 'CSS', 2: 'Loops', a: 'HTML', 1: 'Variables' }
for (const key in lessons) {
console.log(key)
}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 needObject.hasOwn()then. - Don’t add or remove properties while a
for...inloop is running. There’s no guarantee whether new keys get visited. Symbolkeys and non-enumerable properties are skipped.
Related entries
#- for...in vs for...offor...of hands you the successive values of an iterable object, while for...in hands you the successive property names of an object as strings.
- for...ofWalks the successive values of an iterable object: an array, a string, a Map, a Set, and others.
- Object.keys()Returns an array of an object’s own, enumerable property names.
- Object.entries()Returns an array of an object’s [key, value] pairs.
- Object.hasOwn()Checks whether an object has its own property with the given name.
- Object.create()Creates a new object with the given prototype.
Spotted a mistake or missing an example? Write to us.