for...in
- Node.js course
- Beginner
- Lesson 45/116
- 4 min
Learn to iterate over object keys with for...in.
The for...in loop
To walk an object's keys in order you use for...in. The form is for (const key in object) { ... }. On each iteration key takes a key name (as a string).
For example const user = { name: "Alex", age: 25 }; for (const key in user) { console.log(key); } prints name and age in order. To reach the value use user[key]. for...in is designed for objects; using it on arrays is technically possible but discouraged because it can mix indices and properties.
for...in vs for...of
for...in walks object keys; for...of walks iterable elements (array, string, Map, Set). They are designed for different purposes; mixing them leads to errors.
If you try for...of on a plain object you get a TypeError because objects are not iterable. If you try for...in on an array you get the indices ("0", "1", ...) which is usually unwanted. The rule is simple: objects use for...in, arrays use for...of.
Practice Print the object keys
The user variable holds { name: "Alex", age: 25 }. Write a for...in loop: walk each key with const key in user and print it with console.log(key). The output must be two lines: name, age.
Starter code
const user = { name: "Alex", age: 25 };
// Write the for...in loop hereSample solution
const user = { name: "Alex", age: 25 };
for (const key in user) {
console.log(key);
}Expected output
name age
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the output of for (const k in {a: 1, b: 2}) { console.log(k); }?
for (const k in { a: 1, b: 2 }) { console.log(k); }- a b Correct answer
- a 1
- 1 2 a b
- 1 2
Explanation: for...in gives keys; "a" and "b" are printed.
2 Match each construct to its use
| Term | Meaning |
|---|---|
for...of |
Array elements |
for...in |
Object keys |
for (let i...) |
Counted index |
while |
Conditional loop |
3 Write the for...in header
const user = { name: "Alex", age: 25 };
____ (const key in user) {
console.log(key);
}
const user = { name: "Alex", age: 25 };
for (const key in user) {
console.log(key);
}
Explanation: for...in walks object keys.