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]}`);
}
๐งพ Output:
js shortcut is javascript
cpp shortcut is C++
rb shortcut is ruby
swift shortcut is swift by apple
โ๏ธ
for...inis 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]);
}
๐งพ Output:
js
cpp
java
py
โ ๏ธ While
for...inworks with arrays, it actually loops through the indices (0, 1, 2, 3...) and not the values directly.๐ก Pro Tip: Use
for...ofwhen 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);
}
๐งพ Output:
TypeError: map is not iterable using for...in
โ
for...indoes not work with Map objects. Maps are not enumerable in the way objects are. For Maps, usefor...ofwith destructuring.
for (const [key, value] of map) {
console.log(`${key} = ${value}`);
}
๐ง 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)