JavaScript for...in and for...of
`for...in` iterates over the enumerable property names (keys) of an object, while `for...of` iterates over the values of an iterable, like an array, string, Map, or Set.
A common mistake is using `for...in` on arrays โ it technically works but iterates keys as strings and can include inherited properties, so `for...of` is safer for arrays.
for...in for objects
`for (const key in obj) { console.log(key, obj[key]); }` visits each property name of an object.
for...of for iterables
`for (const value of arr) { console.log(value); }` visits each value directly, working on arrays, strings, Maps, and Sets.
let user = { name: "Kim", age: 30 };
for (const key in user) {
console.log(key, user[key]);
}name Kim
age 30for...in visits each property key of the object.
let arr = [10, 20, 30];
for (const val of arr) {
console.log(val);
}10
20
30for...of gives direct access to array values, not indices.
Key points
- for...in iterates over object property keys.
- for...of iterates over values of an iterable (array, string, Map, Set).
- Prefer for...of for arrays to avoid key/inheritance pitfalls.
- Both are cleaner alternatives to manual indexing in many cases.
