Quick .reduce() Question

I was trying to use a different methods in the secretMessage exercise, but I can’t wrap my brain around the different results when adding a simple , ‘’ to the end of the my return-

const animals = [‘Hen’, ‘elephant’, ‘llama’, ‘leopard’, ‘ostrich’, ‘Whale’, ‘octopus’, ‘rabbit’, ‘lion’, ‘dog’];

const secretMessage = animals.reduce((accumulator, x ) => accumulator + x[0]);

console.log(secretMessage); //Outputs: HenelloWorld

Now we add , ‘’ to the end, and we get the desired result with the correct message.

const secretMessage = animals.reduce((accumulator, x ) => accumulator + x[0] , ‘’);

console.log(secretMessage); //Outputs: HelloWorld

So what about the additional , ‘’ corrects this issue?


Hi there and welcome to the forums!
From reading the .reduce documentation, we get this syntax:

array .reduce( function(total, currentValue, currentIndex, arr), initialValue )

Here we can see that the .reduce method can actually take two arguments, the function to iterate with, and the initial value to use. The initial value is optional hence why the iterator does work without it in the first attempt, however the method needs some initial value to be able to carry out the first calculation. Therefore it defaults to taking the first element on its own as the initial value, and starting with the second method. So the first calculation of the two attempts are as follows.

// calculation 1 without initial value
accumulator + x[0]
"Hen" + e

/// calculation 1 with initial value
accumulator + x[0]
"" + "H"

Hence why in this case you need to specify the initial value. Hopefully this makes sense.


Ahhhh, yes the definition makes a lot more sense now. Just needed to see an example of it in action! Very well explained, thank you sir!!

1 Like

It’s a good tip for future debugging, think about what you expect it to do, and then try to follow through the steps of what is actually happening inside the code! Don’t be afraid to put console.log() statements everywhere to identify it. For example here I’d recommend adding a console.log(accumulator) into the reduce, and then you would spot that the very first one was taking “Hen”. Debugging is half the battle!

1 Like