. Advertisement .
..3..
. Advertisement .
..4..
To get the sum of an array in JavaScript, you have many options. Explore these solutions and how you can implement them.
Sum of An Array In JavaScript
With A for Loop
As you may already have in mind, a traditional for loop can help you solve the problem. You can make a loop that iterates through all the elements of an array and adds them one by one. This is one version of using for to get the sum of an array in JavaScript:
function getSum(array){
let sum = 0;
let d = array.length;
for (let i = 0; i < d; i += 1) {
sum += array[i]
}
console.log(sum)
return sum
}
getSum([3, 2]);
getSum([1, 2, 3, 4, 5]);
Output:
5
15
In this implementation, we create a loop that starts from 0 to the value before the length of the array. The reason for this is that arrays in JavaScript use zero-based indexing, meaning elements of an n-member array have indexes ranging from 0 to (n-1).
We start with a zero value for the sum variable first. Each time we access an element of the array, we add its value to this sum with the additional assignment operator (+=
).
What it does is to add the value of the right operand (array[i]
) to the current value of the variable on the left (sum) and assign this result to that variable. String concatenation is possible with this operator, but since both of the operands here are numbers, it just adds another element to the total sum.
After the for loop completes its iteration, the value of the sum value is just also the sum of all the elements of the array. The code above puts the loop inside a function so you can repeat it on any valid array you want.
With Array.reduce()
The reduce()
method of the Array class can execute a reducer (a user-defined callback function) on every element of an array and return a single result.
Like a loop, this reducer iterates through the array. But the special thing about this function is that it takes the return value of the call on the preceding element as its argument.
If the callback is run the first time, there is no previous calculation. You can provide an initial value for this special case or let the reduce()
method pick the first element as the initial value and start the iteration from the second element (which has the index 1).
One of the most common and simplest applications of this method is to evaluate the sum of all elements in an array. There are many ways to make use of this method, one of which is with the arrow function:
reduce((previousValue, currentValue) => { /* … */ } , initialValue)
- previousValue: the returned value of the previous call. In the first call, the initialValue is used.
- currentValue: the value of the current element.
- initialValue: this optional parameter is the initial value for previousValue in the first callback.
Here is how you can rewrite the code in the previous section with the reduce()
method. We use it to define the same getSum()
function, which will be invoked onto the same test arrays:
function getSum(array){
const initialValue = 0;
const sum = array.reduce(
(previousValue, currentValue) => previousValue + currentValue,
initialValue);
console.log(sum)
return sum
}
getSum([3, 2]);
getSum([1, 2, 3, 4, 5]);
Output:
5
15
As you can see, this solution gives the same results as our for loop above. The reducer we use here is ‘previousValue + currentValue
‘, which adds the values of all the elements over time.
Summary
You can use a for loop or the reduce()
method to calculate the sum of an array in JavaScript. They have different syntaxes, but these solutions basically do the same thing: go through all the elements in the array and add their values to the total sum one by one. For more complicated tasks like adding an array to another array, have a look at this guide.
Leave a comment