use reduce to sum a list of numbers in javascript

To use the reduce() method to sum a list of numbers in JavaScript, you can pass a reducer function as an argument to reduce(). The reducer function will take in two parameters: an accumulator and the current value being iterated over.

Here's how to use reduce() to sum a list of numbers in JavaScript:

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

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sum); // Output: 15
171 chars
8 lines

In this example, we first define an array of numbers called numbers. Then, we use the reduce() method to sum the numbers.

Inside the reducer function, we add the accumulator and currentValue parameters, which represent the accumulated value and the current value of the iteration, respectively. We then return the sum of the accumulator and currentValue.

At the end of the reduce() method, we pass in the initial value for the accumulator, which is 0 in this case.

Finally, we log the sum variable to the console, which should output 15 – the sum of the numbers in the numbers array.

gistlibby LogSnag