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.
- 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:
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:
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){
|
for(let value of arr){
|
| Example |
const user = {name:"John", age:35};
|
const nums=[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:
message Success
2. List of Products
let products = ["Phone", "Laptop", "Tablet"];
for (let product of products) {
console.log(product);
}
Output:
Laptop
Tablet
When to Use for…in
You should use for…in when
- Iterating object properties
- Working with dynamic objects
- Accessing keys
When to Use for…of
You should use for…of when
- Iterating arrays
- Working with iterable data
- 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.