---
title: "Why we are use the forEach loop in JS?"  
description: "Why we are use the forEach loop in JS?"  
author: "Ravi Vishwakarma"  
published: 2021-07-19  
canonical: https://answers.mindstick.com/qa/93735/why-we-are-use-the-foreach-loop-in-js  
category: "web application"  
tags: ["javascript", "web development", "web application development"]  
reading_time: 1 minute  

---

# Why we are use the forEach loop in JS?

Why we are use the [forEach loop](https://www.mindstick.com/forum/155785/how-to-use-foreach-loop-in-mvc-razor-view) in JS?

## Answers

### Answer by Ethan Karla

Foreach loop is use to print the data one by one. This is used in array, object, collection to print all data. **Example1:**

```
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>Compute the sum of the values in an array:</p>
<p id='demo'></p>
<script>
let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
document.getElementById('demo').innerHTML = sum;
function myFunction(item) {
  sum += item;
}
```

</script> </body> </html> **Example2:**

```
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
```

**Example3:**

```
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>Multiply the value of each element with 10:</p>
<p id='demo'></p>
<script>
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)
document.getElementById('demo').innerHTML = numbers;
function myFunction(item, index, arr) {
  arr[index] = item * 10;
}
</script>
</body>
</html>
```

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