Condense arrays with reduce - Logic

Hi! I tried experimenting with this particular waypoint and I’m quite confused behind the logic behind it.

This is the default answer to the waypoint, and simply enought, it adds the elements together, resulting in 30.

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

// Only change code below this line.
singleVal = array.reduce(function(x, y) {
  return x + y;

But, if I change the return x + y to return x + x, it yields 64. If I type y + y, it yields 16. Can anyone explain why this is so? Thanks!

The key to using reduce is knowing how the variables in the function work. Actually the function will take up to four arguments but the most important are the first two, x and y in your case.

The first, x in this case, is the accumulated variable. It starts out at an initial value of the first element of the given array (unless you provide the initial value as an argument after the anonymous function) and then becomes whatever you return inside the function as you loop through the array.

The second variable, y, is the current value taken from the provided array.

So if you return x + x you are taking the accumulated value and adding itself once for every array element (except the first). So it is 4, 8, 16, 32, and finally 64.

Now if you try y + y the accumulated value becomes the array element plus itself. We’d get 8, 10, 12, 14, and 16.

1 Like

It often helps to name your variables appropriately. Take a look at this
Instead of calling x as x, I’m going to call it as accumulatedValue. And
Instead of calling y as y, I’m going to call it as currentValue.

singleVal = array.reduce(function(accumulatedValue, currentValue) {
  return x + y;

Does this make sense?

The way reduce works is, it internally iterates over an array and applies the function you’re passing in on each of the elements at current index. Whatever your function returns is passed in as accumulatedValue in the next iteration.

Reduce also takes 2nd option argument called as initialValue. If this value is absent, reduce will fallback to element at 0th index and consider it as initialValue.

Here is how a reduce function is implemented, if that helps you understand it better.

Array.prototype.reduce = function(cb, initialValue) {
    var accumulatedValue = (initialVal === undefined) ? undefined : initialVal;
    for (var i = 0; i < this.length; i++) {
        if (accumulatedValue !== undefined)
            accumulatedValue =, accumulatedValue, this[i], i, this);
            accumulatedValue = this[i];
    return accumulatedValue;
1 Like

Thanks guys! It’s clearer now!