DSA: findSum

Niani Byrd
1 min readOct 17, 2021

Ever thought about fining the sum of all of the numbers in an array? Take a look at two different methods to find the solution. Let’s say for example we have the following array:

numbers = [10, 20, 30, 40, 50]

We’ll begin by creating the variable sum and setting to zero.

let sum = 0

Next, we’ll iterate over the array using a for loop. Within this loop we want to calculate the sum of each element of the array. We accomplish this by typing:

for (let i = 0; i < numbers.length; i++) {
sum += numbers[i]
}

And there you have it! If you console.log the sum, you’ll get the correct output.

console.log(sum) // Output: 150

But is there an easier way to do this? Turns out, JavaScript has a built in method that will calculate the sum of every element in an array! We can use the reduce function. According to the JavaScript MDC Docs, the reduce function “walks through the array element-by-element, at each step adding the current array value to the result form the previous step.” This will happen until there are no more remaining elements to add. We do this by called the reduce method on the array likeso:

let arr = [10, 20, 30, 40];
let sum = arr.reduce(function (a, b) {
return a + b;
}, 0);
console.log(sum); // Output: 100

Console.log the sum and you have the correct answer!

--

--