find the sum of a list of numbers in javascript

To find the sum of a list of numbers in Javascript, you can use the reduce() method on an array. The reduce() method takes a callback function as its first argument, which will be called on each element of the array. The callback function takes two arguments, the accumulator and the current value. To find the sum of the array, you can initialize the accumulator to 0 and add each value to it as the callback function is called.

Here's an example:

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

const sum = nums.reduce((acc, curr) => {
  return acc + curr;
}, 0);

console.log(sum); // 15
125 chars
8 lines

In this example, we initialize the accumulator acc to 0 and add each value curr to it. The result is a sum of all the numbers in the array.

gistlibby LogSnag