Why we are use the forEach loop in JS?

Asked 19-Jul-2021
Viewed 170 times

1 Answer


2

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>