DEV Community

Aman Kumar
Aman Kumar

Posted on

# 🔁 Mastering the `for...in` Loop in JavaScript: When and Where to Use It

JavaScript offers several looping mechanisms, and one of the most misunderstood is the for...in loop. Today, let’s uncover the truth behind for...in, what it’s really good at, and where you shouldn’t use it.


🎯 What is for...in?

The for...in loop is used to iterate over the enumerable properties of an object. It goes through the keys (also called property names) of an object one by one.


🧪 Example 1: for...in on Objects ✅

const myObject = {
    js: "javascript",
    cpp: "C++",
    rb: "ruby",
    swift: "swift by apple"
};

for (const key in myObject) {
    console.log(`${key} shortcut is ${myObject[key]}`);
}
Enter fullscreen mode Exit fullscreen mode

🧾 Output:

js shortcut is javascript
cpp shortcut is C++
rb shortcut is ruby
swift shortcut is swift by apple
Enter fullscreen mode Exit fullscreen mode

✔️ for...in is perfect for objects because it loops through each key.


🧪 Example 2: for...in on Arrays 🔎

const programming = ["js", "cpp", "java", "py"];

for (const key in programming) {
    console.log(programming[key]);
}
Enter fullscreen mode Exit fullscreen mode

🧾 Output:

js
cpp
java
py
Enter fullscreen mode Exit fullscreen mode

⚠️ While for...in works with arrays, it actually loops through the indices (0, 1, 2, 3...) and not the values directly.

💡 Pro Tip: Use for...of when you want to iterate through values in an array.


🧪 Example 3: for...in on Maps 🚫

const map = new Map();
map.set('IN', "India");
map.set('USA', "America");
map.set('Fr', "France");

for (const [key, value] in map) {
    console.log(key, '=', value);
}
Enter fullscreen mode Exit fullscreen mode

🧾 Output:

TypeError: map is not iterable using for...in
Enter fullscreen mode Exit fullscreen mode

for...in does not work with Map objects. Maps are not enumerable in the way objects are. For Maps, use for...of with destructuring.

for (const [key, value] of map) {
    console.log(`${key} = ${value}`);
}
Enter fullscreen mode Exit fullscreen mode

🧠 Quick Recap

Data Type Use for...in? Why?
Object ✅ Yes Loops through keys
Array ⚠️ Not recommended Loops through indices, not values
Map ❌ No Not enumerable like objects

🔚 Final Thoughts

Understanding where for...in shines can save you from subtle bugs and confusion. Use it wisely—especially when dealing with objects. For arrays and maps, go with for...of instead.

Top comments (0)