Need a little help understanding reduce !☻

Need a little help understanding reduce !☻


Hello there !
I have trouble understanding the different parameters of the reduce callback function, look at this :

var array = [4,5,6,7,8];
var singleVal = 0;

// Only change code below this line.
singleVal = array.reduce(function(previousVal,currentVal){
  return previousVal + currentVal;
}, 0);

I’m talking about “previousVal” and “currentVal”, can we just add whatever number of parameters, like I can put (previousVal,currentVal,afterVal,afterVal2,afterVal3) ?

And what they refer to ?
I mean when we are at the first iteration, it’s previousVal (= 0) + currentVal (= 4) right?

Thank’s if someone respond :slight_smile:
(sorry for the grammar mistakes if there is).


I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

The arguments used in the callback function for reduce represent very specific values. See the documentation here. There are four possible arguments. The first two (the accumulator and the current array item) are the most commonly used, but the third (the index of the current item) and the fourth (the actual original array in which the reduce function was called) can be useful in some solutions.

In the documentation, you will also see an initialValue parameter which defines the initial value of the accumulator. If this is not specified, then the accumulator argument is assigned the first element of the array and reduce iterates starting with the 2nd element of the array.

You can give all the arguments whatever name you choose. In the example you provide, the accumulator is named previousVal, because it represents the current sum after the previous iteration. The currentVal represents the current item. Since curreVal is the 2nd argument of the callback, it is the current item of the array, so this naming makes sense.


The callback function will only know how to handle the 4 parameters described here.


Thank’s guys it helped ! I’ll sleep less idiot tonight