Most JavaScript Developers are confused about for… in and for… of when looping over objects and arrays, so in this tutorial, you will learn to clear the difference between for… in and for…of loops.
In this tutorial, you will learn
- What for…in does
- What for…of does
- When to use each
- Real-world mistakes
- Interview questions
Quick Comparison Table
| Feature | for…in | for…of |
|---|---|---|
| Works on | Object | Iterable (Array, String, Map, Set) |
| Returns | Keys (indexes) | Values |
| Best for | Objects | Arrays |
| ES Version | ES5 | ES6 |
| Use with array? | ❌ Not recommended | ✅ Recommended |
What is for…in Loop?
for…in is used to iterate over the keys of an Object.
This is best for looping over Objects.
Example:
const employee = {
"name": "John",
"salary": 100000,
"department": "Lead Developer"
}
for(let key in employee) {
console.log(key);
}
Output is
age
What is for…of Loop?
for…of is used to iterate over values of iterable objects.
This is best for arrays, strings, maps, and sets.
Example:
const arr = [10, 20, 30, 40, 50]
for(let value of arr) {
console.log(value);
}
Output:
20
30
40
50
Real-World Mistake
Suppose you want to get a value from the array through a for… in loop, then it will get keys instead of values.
❌ Wrong Usage
const arr = [10, 20, 30]
for(let value in arr) {
console.log(value);
}
Output is
1
2
✅ Correct Usage
const arr = [10, 20, 30]
for(let value of arr) {
console.log(value);
}
Output:
20
30
When to Use for…in and for…of ?
When to use for…in?
- When you need property name.
- When you need looping over an object.
When to use for…of?
- When you need values.
- When you need looping over an array.
for… in vs for… of – Objective Questions (MCQs)
Q1. for...in iterates over ______, while for...of iterates over ______.
Q2. Which loop is best suited for arrays?
Q3. for...in can iterate over ______ properties.
Q4. Which loop works with iterable objects like Map and Set?
Q5. Which loop returns indexes when used with arrays?