When you’re working with loops in JavaScript, it’s common to get confused between for...in
and for...of
. Both look similar, but they serve different purposes. Let’s break it down 👇
🍏 Example
const myArray = ["apple", "banana", "cherry"];
// for...in loop → iterates over indices
for (const index in myArray) {
console.log(`Index: ${index}, Value: ${myArray[index]}`);
}
// Output:
// Index: 0, Value: apple
// Index: 1, Value: banana
// Index: 2, Value: cherry
// for...of loop → iterates over values
for (const value of myArray) {
console.log(`Value: ${value}`);
}
// Output:
// Value: apple
// Value: banana
// Value: cherry
⚖️ Key Difference
-
for...in
→ iterates over the keys (or indices). -
for...of
→ iterates over the values.
🛠️ When to Use
- âś… Use
for...in
→ when you need the index or keys (mostly for objects). - ✅ Use
for...of
→ when you need the values (perfect for arrays, strings, maps, sets).
đź’ˇ Note: You can use
for...in
with arrays, but it’s not recommended — usefor...of
instead.
🎯 Real-Life Analogy
Imagine you have a shopping list:
const shoppingList = ["Milk", "Eggs", "Bread"];
-
for...in
→ You’re checking the shelf number (0, 1, 2). -
for...of
→ You’re directly picking up the items (Milk, Eggs, Bread).
✨ Summary
- Use
for...in
→ when you want indexes/keys. - Use
for...of
→ when you want values.
Keep this in mind and you’ll never mix them up again! 🚀
👍 Did this help you? Drop a comment with how you use loops in your projects!
Top comments (0)