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)