Second parameter in a high order function

Hi, made a lot of progress in my knowledge about high order functions and callback functions, but with introducing a second parameter in a high order function, you lost me again.

the lesson link is:

β€œThe .reduce() method can also take an optional second parameter to set an initial value for accumulator (remember, the first argument is the callback function!). For instance:”

const numbers = [1, 2, 4, 10];

const summedNums = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue
}, 100)  // <- Second argument for .reduce()

console.log(summedNums); // Output: 117

So I understand that we have a method/function β€œ.reduce()” with as parameters a callback function β€œ(accumulator, currentValue) => {
return accumulator + currentValue
}” and a value of 100. (and the callback function has 2 parameters (accumulator and currentValue)

what I dont understand is, why does the value 100 get assigned to the first parameter of the callback function?

thanks as always :slight_smile:

Scroll down to Syntax and study the template. Note where the initial value is written as the last argument (second parameter) of the reduce method.

const newSum = newNumbers.reduce(
  (accumulator, currentValue) => accumulator + currentValue, 

The first parameter is the callback function, the second is the initial value.

Okay great, I think I get it.

made this picture to make it more clear for myself:

if I dont make it as a programmer, i could always try to become a paint-pro :grin:

1 thing that i didnt understand in the syntax on the developer website:

" callback

A function to execute on each element in the array (except for the first, if no initialValue is supplied)."

So it will skip the first element in the array if no initialValue is assigned? In the first example in the lesson there is no inital value, and in the first iteration the function takes number[0] as accumulator and numbers[1] as currentValue. I dont see the 'except for the first" part.


1 Like

If there is no initial value provided (the second argument) then the initial value is the first element in the array. Iteration begins on the second value in the array, which is accumulated.

 [1, 2, 3, 4, 5]
 1 + 2
 3    + 3
 6       + 4
 10         + 5
 => 15