JavaScript Difference: for…in vs for…of

Introduction

Understanding the difference between these two loops is extremely important, especially when working with arrays, objects, and iterable data structures.

In this guide, you’ll learn the complete difference between for…in and for…of, including syntax, examples, real-life use cases, comparison tables, common mistakes, and interview questions.

📖
Best Practices:
  • Use for…in for objects.
  • Use for…of for arrays and iterables.
  • Avoid using for…in on arrays.

What is for…in Loop?

The for…in loop is used to iterate over the keys (property names) of an object.

Syntax of for…in


for (let key in object) {
   // code
}

Example of for…in


let user = {
   name: "John",
   age: 35
};

for (let key in user) {
   console.log(key);        // name, age
   console.log(user[key]);  // John, 25
}

Output:

name
John
age
35

Note:  It returns keys, not values.

What is for…of Loop?

The for…of loop is used to iterate over the values of iterable objects.

Syntax of for…of Loop


for (let value of iterable) {
   // code
}

Example of for…of Loop


let arr = [10, 20, 30];

for (let value of arr) {
   console.log(value); // 10, 20, 30
}

Output:

10
20
30

Note: It returns values, not keys.

Key Difference (Quick Summary)

Feature for…in for…of
Iterates Keys Values
Works With Objects Iterables
Output Property names Actual values
Best Use Objects Arrays, Strings
Syntax for(let key in obj){
  console.log(key);
}
for(let value of arr){
  console.log(value);
}
Example const user = {name:"John", age:35};

for(let key in user){
  console.log(key);
}

Output:
name
age
const nums=[10,20,30];

for(let value of nums){
  console.log(value);
}

Output:
10
20
30

Real-Life Examples

You will see some real-life examples

1. Get API Response(Object)


let response = {
   status: 200,
   message: "Success"
};

for (let key in response) {
   console.log(key, response[key]);
}

Output:

status 200
message Success

2. List of Products


let products = ["Phone", "Laptop", "Tablet"];

for (let product of products) {
   console.log(product);
}

Output:

Phone
Laptop
Tablet

When to Use for…in

You should use for…in when

  1. Iterating object properties
  2. Working with dynamic objects
  3. Accessing keys

When to Use for…of

You should use for…of when

  1. Iterating arrays
  2. Working with iterable data
  3. Accessing values directly

Conclusion

Both for…in and for…of loops are powerful tools in JavaScript, but they serve different purposes. While for…in is ideal for iterating over object properties, for…of is best suited for iterating over iterable values like arrays, strings, and maps.

Related JavaScript Tutorials