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)