The sum of an array of numbers can be calculated in a variety of ways, including:
Let’s check out each of them one by one!
Method 1: Calculate the Sum of an Array of Numbers Utilizing for Loop
To calculate the sum of an array of numbers, the most basic and traditional method is the “for” loop. In this approach, iterate the array to the length and add them.
Utilize the following syntax to use the for loop:
Create an array of numbers:
Create a variable “arrayElementSum” and set its initial value to 0:
Add the elements of an array by iterating the array until the array’s length using for loop:
arrayElementSum += array[i];
Print the sum of the array’s elements using the “console.log()” method:
The output shows the sum of all the elements in an array as “65”.
Calculate the Sum of an Array of Numbers Utilizing for-of Loop
Let’s use the for-of loop for each iteration of the array to add the array elements:
arrayElementSum += sum;
The output indicates that with the help of the “for-of” loop, the elements of an array that are successfully added and displayed “65” as their sum.
Calculate the Sum of an Array of Numbers Utilizing forEach Loop
Use the same array created in the previous example and loop across the array using the array.forEach() loop method:
arrayElementSum += sum;
Method 2: Calculate the Sum of an Array of Numbers Utilizing reduce() Method
Follow the below-provided syntax for using the reduce() method:
In the above syntax:
- The method takes two parameters, the callback function, or the initialValue.
- The callback function further calls some parameters, including “preValue”, “currentValue”, “currentIndex”, and an “array”, where the last two parameters are optional.
Use the below lines of code while using the “reduce()” method for adding the elements of the array:
return a + b;
- To iterate across the array, use the reduce() method on Array.
- Set the reduction method’s initial value to 0.
- It returns the sum of the current value and the collected value at the end of each iteration.
For getting the sum of the elements of a number array, the “for” loop, “for-of” loop, “forEach” loop, or the “reduce()” method is used. Iterative loops are useful for calculating the sum of array elements because they seek to consider each element separately. All the mentioned approaches are discussed in this article with examples.