ES6 Rest Parameter(...arg): Need more in depth explanation

const sum = (x, y, z) => {
const args = […args];
return args.reduce((a,b) => a + b, 0);
}

I understand that …args takes in a variable number of arguments. What I am getting hung up on is that suddenly we have two parameters, a and b in the return function statement. May someone please explain to me why that is? What exactly is going on with the inputs that we went from x, y, z (3 parameters) to variable number of arguments, and now there is a function that only has a and b (2 parameters). What happened to the 3rd parameter? I am not necessarily looking for the answer to the problem, rather the way this data is moving thru this system.

Thank you in advance for taking the time to read my question. Much appreciated.

Hey!

So reduce method is a complex one but will try to explain you at my best here…

So as a method it takes 4 arguments in general but here you have 2 since you want the sum of your array of numbers: the a is the accumulator and the b is the total, the 0 it means that it starts from 0 index. So basically check what exactly is happening below:

lets say you have const nums = [1, 2, 3 ]

at the reduce method what is happening is:

Iteration: 1 (first iteration not number!) , Iteration: 2. Iter: 3

Accumulator: 0 (index 0 in your case) Acc: 1. Acc: 3

Num: 1 Num: 2. Num: 3

return: 1 Return: a + b = 3. Ret: a+b=6

So as you see the return value adds up to the accumulator every time.
reduce
Hope that helps

1 Like

I really appreciate this answer. You were thorough with your explanation and the visual was very helpful. I usually can figure out the problems on my own, so I suspected it was some sort of format for the reduce method. I could not find explanations about this even in the YouTube tutorials for this problem.

Big thanks!

No worries,

Glad it helped…reduce is a beautiful and powerful method…
You could practise here:


It has a playground and you can solve challenges and learn more about JavaScript…and is for free…

Have a good night

1 Like

For others who see this posted question and want more examples, I found another YouTube explanation that supplements what VickyV posted for reduce method. Also, Kodiri looks like a fun way to practice:

1 Like