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...inwith arrays, but itโs not recommended โ usefor...ofinstead.
๐ฏ 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)