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...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]);
}
🧾 Output:
js
cpp
java
py
⚠️ 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);
}
🧾 Output:
TypeError: map is not iterable using for...in
❌
for...in
does not work with Map objects. Maps are not enumerable in the way objects are. For Maps, usefor...of
with 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)