Get the Sum of an Array of Numbers using Array.reduce() method.
To get the sum of an array of numbers:
- Use the
reduce()
method to iterate over an array. - To get started, set the initial value in the reduce method to 0.
- On each iteration, add the current number to the sum of all previous numbers.
Example –
const theArray = [2, 55, 100];
const sum = theArray.reduce((accumulator, value) => {
return accumulator + value;
}, 0);
console.log(sum);
Here’s what the above code is doing:
- The
reduce()
method takes two arguments: a callback function and an initial value. - The callback function takes two arguments: an accumulator and the current value.
- The accumulator is like a total that
reduce()
keeps track of after each operation. - The current value is just the next element in the array that
reduce()
is iterating over. - The initial value sets the accumulator to
0
. - The callback function adds the current value to the accumulator.
- The
reduce()
method returns the final value of the accumulator.
Get the Sum of an array of numbers using a for…of loop.
To get the sum of an array of numbers:
- Declare a
sum
variable and set it to0
. - Use the for…of loop to iterate over the array.
- On each iteration, add the value of the current element to the sum variable.
Example –
const theArray = [2, 55, 100];
let sum = 0;
for (const value of theArray) {
sum += value;
}
console.log(sum);
Here’s what the above code is doing:
- We create an array called
theArray
. - We create a variable called
sum
and set it to0
. - We use a
for...of
loop to loop overtheArray
. - We add the value of the current element to
sum
. - We log the value of sum to the console.
âšī¸ The for…of loop is a great way to loop over arrays.
Get the sum of an array of numbers using a for
loop.
To get the sum
of an array of numbers:
- Declare a
sum
variable and set it to0
. - Use the
for
loop to iterate over the array. - On each iteration, add the value of the current element to the
sum
variable.
Example –
const theArray = [2, 55, 100];
let sum = 0;
for (let index = 0; index < theArray.length; index++) {
sum += theArray[index];
}
for
loop.Here’s what the above code is doing:
- We create a variable called
sum
and set it equal to0
. - We create a
for
loop that will run as long as the index is less than the length of the array. - We add the value of the current index to the
sum
variable. - We increment the index by
1
. - We repeat steps 2-4 until the index is no longer less than the length of the array.
- We log the
sum
variable to the console.
đī¸ Thereduce()
method is the best way to get the sum of an array of numbers in JavaScript. Afor...of
orfor
loop would be less efficient.