Use of the number "0" in Condense arrays with reduce

Tell us what’s happening:
What is the purpose of “0” which is used after the curly brackets end in the “singleVal” variable.

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;
}, 0);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36.

Link to the challenge:

1 Like

reduce takes two arguments, a function, and the initial value. by default the initial value is the first element in the array, but you can explicitly give it a value.

reduce turns an array of values into another value: it takes the previous value, then performs an operation on that and the current value. Then the output of that becomes the previous value, and it performs an operation on that and the current value and so on.

So you have a function like:

function add(previousValue, currentValue) {
  return previousValue + currentValue;

and an array:


so initially, previousValue is 0, currentValue is 1. 0 + 1 is 1. previousValue is now 1, current value is 2, 1 + 2 is 3. previousValue is now 3, current value is 3, 3 + 3 is 6. And so on.