for...of & for...in Loops
for...of iterates over values (arrays, strings, Maps). for...in iterates over keys (object properties). Using the right one avoids common bugs.
for...of vs for...in
- for...of — Iterates VALUES: for (const item of array). Use with arrays, strings, Maps, Sets
- for...in — Iterates KEYS/INDICES: for (const key in object). Use with objects
- ⚠️ Don't use for...in on arrays — It iterates indices as strings, not values. Also includes inherited properties
- for...of on strings — Iterates each character: for (const char of 'hello')
- When to use — for...of for arrays/strings. for...in for object keys. forEach/map for array transforms
for...of & for...in Code
// for...of — iterate VALUES (arrays, strings)
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color); // "red", "green", "blue"
}
// for...of with strings
for (const char of "Hello") {
console.log(char); // "H", "e", "l", "l", "o"
}
// for...in — iterate KEYS (objects)
const user = { name: "Alice", age: 25, role: "Admin" };
for (const key in user) {
console.log(`${key}: ${user[key]}`);
}
// name: Alice, age: 25, role: Admin
// ❌ DON'T use for...in on arrays
const nums = [10, 20, 30];
for (const i in nums) {
console.log(typeof i); // "string" — i is "0", "1", "2" not 0, 1, 2
}
// ✅ Use for...of for arrays
for (const num of nums) {
console.log(num); // 10, 20, 30 (actual values)
}Tip
Tip
Use for...of for arrays and strings (iterates values). Use for...in for plain objects (iterates keys). Use forEach/map/filter for array transformations. This simple rule prevents most iteration bugs.
Generators produce values lazily. yield pauses execution. Great for infinite sequences + async.
Common Mistake
Warning
Using for...in on arrays iterates indices as strings ('0', '1', '2'), not numbers, and also includes inherited prototype properties. This causes subtle bugs. Always use for...of or .forEach() for arrays.
Practice Task
Note
Compare iteration methods: (1) Use for...of to iterate an array of colors and log each. (2) Use for...in to iterate a user object and log key: value pairs. (3) Use for...of on a string to count vowels.
Quick Quiz
Key Takeaways
- for...of — Iterates VALUES: for (const item of array). Use with arrays, strings, Maps, Sets
- for...in — Iterates KEYS/INDICES: for (const key in object). Use with objects
- ⚠️ Don't use for...in on arrays — It iterates indices as strings, not values. Also includes inherited properties