for…in vs for…of in JavaScript

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

  1. What for…in does
  2. What for…of does
  3. When to use each
  4. Real-world mistakes
  5. 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

name
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:

10
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

0
1
2

✅ Correct Usage


const arr = [10, 20, 30]
for(let value of arr) {
   console.log(value);
}

Output:

10
20
30

When to Use for…in and for…of ?

When to use for…in?

  1. When you need property name.
  2. When you need looping over an object.

When to use for…of?

  1. When you need values.
  2. 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?