For...of vs For...in: Key Differences
You'll learn how to choose between for...of (which iterates over values) and for...in (which iterates over keys) based on what you need from your loop.
The Core Distinction
Think of for...of and for...in as two different ways to explore a collection:
for...ofasks: "What values are inside this collection?"for...inasks: "What keys (or property names) does this collection have?"
When to Use For...of
Use for...of when you care about the actual data in an iterable:
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color); // 'red', 'green', 'blue'
}
Perfect for arrays, strings, Sets, and Maps where you want the contents.
When to Use For...in
Use for...in when you need the property names of an object:
const user = { name: 'Alice', age: 30, city: 'NYC' };
for (const key in user) {
if (user.hasOwnProperty(key)) {
console.log(key); // 'name', 'age', 'city'
console.log(user[key]); // Access the value if needed
}
}
Best suited for plain objects when you need to know what properties exist.
Quick Decision Guide
- Iterating an array? Use
for...ofto get each element directly - Exploring object properties? Use
for...into get each key name - Need both index and value in an array? Use a regular
forloop orfor...ofwith array methods (once you learn those) - Avoid:
for...inon arrays (gives you string indices, includes inherited properties)
Key Takeaway: Choose for...of to loop through values in iterables like arrays; choose for...in to loop through property keys in objects. Matching the loop type to your data structure prevents confusion and bugs.