I choose not to use the ,0 part and I passed the exercise immediately. Could someone please explain to me what the reason is why the example added ,0 ?
Thanks guys.
Your code so far
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;
});
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36.
This comes from the definition of the Reduce fonction Array.prototype.reduce(callback[, initialValue])
As you can see, the 0 parameter was the initialValue which is optional with 2 cases:
No value passed
The first reduce() call will have previousVal set with the first element , and currentVal set to the second element.
In short, previousVal = arr[0] and currentVal = arr[1]
Value passed
The first reduce() call will have previousVal set with initialValue and currentVal to the first element.
In short, previousVal = initialValue and currentVal = arr[0]
in this the callback functions have optional arg. of (currentIndex and array)
the reduce function has second argument ( first one being the callback function) as the InitialValue
this means that the initial value will start from 0
The initial return value to the accumulator would be ( currentValue+5) for the first time
and then keeps on going as normal
Edit: If you still don’t understand you can checkout this site:
Took me a while to read it over and over what you said and was written, but I understand what you say. I wonder now, as the initial value is passed as 0, which is the first index in the array, it will do exactly the same as when you pass no initial value right? Passing an initial value would only be necessary if the index you want to start with is > 0. Do I get it right like this?
I totally didn’t see the var in the beginning… I just realized that you don’t need to create a var twice so deleting var and the 0 is the only thing you need to do and change the - into a +. However, the logic behind the method is still a little confusing.