Quick question about condensing arrays with reduce

A very general question. I was able to do the assignment for this chapter, but I did have a very quick question. I’ve pasted the exercise so you can understand my question:

  1. who has defined previousNumber and currentNumber…Will JavaScript always recognize those names?
  2. why do we have to use 0 on the last line? If I don’t include 0, it stills works.

In advance, thanks for your guidance!

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);

1 Like

You can name them anything you want. However it’s the position that matters. The first parameter holds the previous return value of the callback function (or the initial value, more on that below). The second one holds the current element while iterating over the array.

It’s the optional initial value. If you provide an initial value, .reduce will start iterating over the array from the first element, and previousVal will hold that value. If you didn’t provide one, the initial value will be the array’s first element, and .reduce will start iterating from the second element.

Note that if you didn’t provide an initial value, .reduce will throw an error if the array is empty.

  1. You can call arguments anything you like (previous/current, prev/curr, foo/bar, myAmazingArg1/myAmazingArg2, accumulator/val)
  2. The parameter at the end is the initial value that the operation will start with (the first previousVal. If you don’t pass that, reduce will assume the first value in the array is the one you want to use)

@kevcomedia @SkyC @DanCouper Thank you all so very much!!! This is very helpful!!!