Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
To get the sum of an array of numbers:
Array.reduce()
method to iterate over the array.reduce
method to 0
.const arr = [5, 15, 45]; const sum = arr.reduce((accumulator, value) => { return accumulator + value; }, 0); console.log(sum); // 👉️ 65
The accumulator
parameter is initially set to 0
because that's what we
passed as the second argument to the
reduce
method.
accumulator
and the current array element.An alternative and perhaps simpler approach is to use a for...of
loop.
To get the sum of an array of numbers:
sum
variable and initialize it to 0
.for...of
loop to iterate over the array.sum
variable to its current value plus the
value of the current element.const arr = [5, 15, 45]; let sum = 0; for (const value of arr) { sum += value; } console.log(sum); // 👉️ 65
The for...of loop allows us to iterate over an array.
sum
variable using the let
keyword. Had we declared the variable using const
, we wouldn't be able to reassign it.On each iteration, we reassign the sum
variable to its current value plus the
value of the current element.
You can also use a basic for
loop to sum an array of numbers.
const arr = [5, 15, 45]; let sum = 0; for (let index = 0; index < arr.length; index++) { sum += arr[index]; } console.log(sum); // 👉️ 65
This example achieves the same goal, but instead of using for...of
we used a
basic for
loop.