Reduce callback function sums all the numbers in an array

PHOTO EMBED

Thu Jul 18 2024 16:18:58 GMT+0000 (Coordinated Universal Time)

Saved by @destinyChuck #html #css #javascript

function sum(...numbers) {
  // The rest operator is three dots followed by the variable name; by convention, it is typically called 'rest'
  // The rest operator must be the last parameter in the function definition
  return numbers.reduce((acc, val) => acc + val, 0);
}   // The reduce method is used to sum all the numbers in the array
content_copyCOPY

The "sum" function takes in an array of numbers using the spread operator and then uses the "Reduce" callback function to sum all of the numbers in the array. Mozilla link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce