Tell us what’s happening:
I spent a while working on this and I finally found the answer in a forum because I could not figure it out. What is the ,0 for? I was also wondering how a+b, 0 is 6 instead of 3. ANd why is it a,b instead of a,b,c???
Your code so far
const sum = (function() {
"use strict";
return function sum(x, y, z) {
const args = [ x, y, z ];
return args.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3)); // 6
const sum = function sum(...args ) {
return args.reduce((a, b) => a + b, 0);
};
console.log(sum(1, 2, 3)); // 6
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.
The a + b is because a is the previous value and b the current value, the result, which is returned, becomes the previous value for the next call, in the reduce function.
I struggled with this one too. At first, I thought that 0 was a default value. Turns out I was wrong. So thank you for bringing up this question, because it made me curious and led me to explore more on this topic.
So here is what I found out googling around:
Turns out the 0 is an initial value.
And I was able to confirm using your code so far:
const sum = function sum(...args ) {
//return args.reduce((a, b) => a + b, 0);
return args.reduce((a, b) => a + b, 4);
};
console.log(sum(1, 2, 3)); // 6
Here I changed the 0 to a 4. And now console.log prints out 10 instead of 6.
Why is it a,b instead of a,b,c?
Let me try to take a stab at this:
From what I understand, the reduce function is like a logic to give to the computer to take an array, and reduce it down to just one number. So I would imagine an array with a million entries instead, not just 3 (e.g. a, b, c). And at the end of the day, I just want one number by adding all the entries together.
And the reduce logic we give it is to say "Hey reduce, take one entry (a), and take another entry (b), add them together (a + b), and put that number back into the front of the array(?). And now do the same thing over, until there is only 1 number left. And you can start counting from the initialValue if it is provided?
Actually I’m a little skeptical about the “put the number back into the front of the array” thing. It’s mostly for illustrative purposes. I don’t know if that actually happens or not. Just how I think of the process.
I hope that was somewhat helpful. And happy camping!