DEV Community

Usama
Usama

Posted on

🔄 JavaScript Loops Explained: for...in vs for...of"

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
Enter fullscreen mode Exit fullscreen mode

⚖️ 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 — use for...of instead.


🎯 Real-Life Analogy

Imagine you have a shopping list:

const shoppingList = ["Milk", "Eggs", "Bread"];
Enter fullscreen mode Exit fullscreen mode
  • 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)