---
title: "Why we are use the for-in loop. What are difference between the foreach and for-in loop?"  
description: "Why we are use the for-in loop. What are difference between the foreach and for-in loop?"  
author: "Ravi Vishwakarma"  
published: 2021-07-19  
canonical: https://answers.mindstick.com/qa/93739/why-we-are-use-the-for-in-loop-what-are-difference-between-the-foreach-and-for-in-loop  
category: "web application"  
tags: ["javascript"]  
reading_time: 1 minute  

---

# Why we are use the for-in loop. What are difference between the foreach and for-in loop?

Why we are use the for-in loop. What are [difference](https://yourviews.mindstick.com/story/5016/chia-vs-basil-seeds-what-s-the-difference) between the foreach and for-in loop?

## Answers

### Answer by Ethan Karla

**forEach** is an Array method that we can use to execute a function on each element in an array. It can only be used on Arrays, Maps, and Sets. A simple example would be to display each element of an array. Here’s what this might look like with for loop. **Example:**

```
const arr = ['cat', 'dog', 'fish'];
arr.forEach(element => {
  console.log(element);
});
```

```
let text = '';
const fruits = ['apple', 'orange', 'cherry'];
fruits.forEach(myFunction);
function myFunction(item, index) {
  console.log('index : '+index+' , item : '+item);
}
```

**For-in loop** For-in is used to iterate over the enumerable properties of objects. Every property in an object will have an Enumerable value — if that value is set to true, then the property is Enumerable.

```
for (variable in object) {
// do something
}
```

**Example:**

```
const obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4
}
for (let elem in obj) {
  console.log( obj[elem] )
}
```

\


---

Original Source: https://answers.mindstick.com/qa/93739/why-we-are-use-the-for-in-loop-what-are-difference-between-the-foreach-and-for-in-loop

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
