Quick question about condensing arrays with reduce


#1

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


#2

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.


#3

The names previousVal and currentVal are defined by you. They are variables that JavaScript will use internally when reducing the array. We see a and b used a lot as well.

As for the 0, that’s a starting value. It defaults to the first number in the aray if you don’t specify anything. In this example, singleVal is equal to 30:

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

singleVal = array.reduce(function (a, b){
  return a + b;
}, 0); // 0 + 4 + 5 + 6 + 7 + 8 = 30

In this one, we change 0 to 12 and it is equal to 42 instead:

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

singleVal = array.reduce(function (a, b){
  return a + b;
}, 12); // 12 + 4 + 5 + 6 + 7 + 8 = 42

This has no starting value defined, so we start at 4 (the first element of the array), which returns 30:

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

singleVal = array.reduce(function (a, b){
  return a + b;
}); // 4 + 5 + 6 + 7 + 8 = 30

#4
  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)

#5

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