Create a function that takes an array and returns the sum of all numbers in the array. code example

Example 1: sum the all values from an array

var numbers = [3, 5, 7, 2];
var sum = numbers.reduce((x, y) => x + y);
console.log(sum); // returns 17

// other way

x = sumAll(1, 123, 500, 115, 44, 88);

function sumAll() {
  var i;
  var sum = 0;
  for (i = 0; i < arguments.length; i++) {
    sum += arguments[i];
  }
  return sum;
}

Example 2: how to add up all numbers in an array

const numbers = [10, 20, 30, 40] 
add = (a, b) =>  a + b
const sum = numbers.reduce(add)

Example 3: js array sum

console.log(
  [1, 2, 3, 4].reduce((a, b) => a + b, 0)
)
console.log(
  [].reduce((a, b) => a + b, 0)
)

Tags: