Why we are use the forEach loop in JS?

0 votes
29 views
Ravi Vishwakarma asked 10 days ago in Web Application by Ravi Vishwakarma

Why we are use the forEach loop in JS?    

1 Answer

1 votes
Ethan Karla answered 8 days ago 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>