PASSWORD RESET

Your destination for complete Tech news

How to find the sum of an array of numbers in Javascript?

375 0
< 1 min read

To find the sum of an array of numbers in JavaScript, you can use the reduce() method. The reduce() method allows you to apply a function to each element in the array, reducing the array to a single value.

Here’s an example of how you can use the reduce() method to find the sum of an array of numbers:

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((total, current) => total + current, 0);

console.log(sum); // Output: 15

In this example, the reduce() method iterates over the numbers array and applies the function to each element. The function takes two arguments: total and current. total is the accumulated value, and current is the current element being processed. The function adds total and current together and returns the result, which is then passed to the next iteration as the new value of total.

The reduce() method also takes an optional second argument, which is the initial value of the total argument. In this example, we pass 0 as the initial value, so the first iteration will use 0 as the value of total and 1 as the value of current.

You can also use the for loop to find the sum of an array of numbers:

const numbers = [1, 2, 3, 4, 5];

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

console.log(sum); // Output: 15

This loop iterates over the numbers array and adds each element to the sum variable. At the end of the loop, sum will contain the sum of all the elements in the numbers array.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.