How to sum values using forEach() method in JavaScript?
In this article, you are going to learn how to use the forEach() method to sum values in an array in JavaScript. Here is an example :
<script> let myArray = [1, 2, 3, 4, 5]; let sum = 0; myArray.forEach(function(e){ sum += e; }); console.log(sum); // Output: 15 </script>
In the above example, we declare a new array called myArray and initialize it with five integers. Then, we declare a variable called sum and set it to 0. We use the forEach() method to iterate over each element in the array and add it to the sum variable.
The forEach() method takes a callback function as its argument. In this function, we use the argument e to access the current element in the array and add it to the sum variable.
Finally, we print the value of sum to the console and the output is 15.
The forEach() method can also take a second argument to store the current index value of the current element. Here is an example : (Below we use arrow function)
<script> let myArray = [1, 2, 3, 4, 5]; let sum = 0; myArray.forEach((e , index) => { sum += e; console.log(index) // Output : 0,1,2,3,4 }); console.log(sum); </script>
How to sum values using forEach() method in JavaScript. #
- Declare a variable to hold the sum and set it to 0.
- Use the forEach() method to iterate over your array.
- Inside the forEach() method, add the current element to the sum variable.
- After finishing the forEach() method, the sum variable will contain the total.
- You can access each element of an array using the forEach() callback function's first argument.
- The forEach() method doesn't return anything, so you must update the sum variable inside the callback function.
- The forEach() method can also take a second argument, which specifies the this value for use inside the callback function.
save
listen
AI Answer
How to sum values using forEach() method in JavaScript?
0
In this article, you are going to learn how to use the forEach() method to sum values in…
asked
Apu
0 answers
2915
In this article, you are going to learn how to use the forEach() method to sum values in…
Answer Link
answered
Apu