What is the use of the 0 ? - ES6 - Use the Rest Parameter with Function Parameters

Hi everyone !

I was wondering what was the use of the 0 in this function.
Was it for the default value of a ?
In this way of view, if i multiply instead of additioning, it always return 0

Also, the “args” given is a standard method in javascript ? Can i change it to any value ?
Also, we are only incrementing a, b, what is the procedure behind it to add more values ? (additional question)

I have some troubles to understand it :slight_smile:

Your code so far

const sum = (...args) => args.reduce((a, b) => a + b, 0);


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

Challenge: ES6 - Use the Rest Parameter with Function Parameters

Link to the challenge:

args.reduce((a, b) => a + b, 0)

a is the final result you will get from reduce
0 at the end is the initial value of the a
b represents every item in the array
So when you use reduce it will take every b one by one
and perform operation e.g.( + ) with the final value assume a
and records the result in a
In this case it is 0 you can change initial value to anything.

1 Like

Hi !

Thanks for your answer, everything is much more clearer :slight_smile:
Thanks !

Actually, in this case you could leave that off. If you don’t give reduce a second parameter, it will just use the first element and skip it. So,

const sum = (...args) => args.reduce((a, b) => a + b);

will give the same answer but with one fewer iteration. And slightly cleaner code.

1 Like

Thanks for your help ! I will have to dig deeper in this matter :slight_smile:

Just to be clear, a is the “accumulator”. It is the result being passed from the previous iteration. It is not the final result. The final result will be returned but reduce.

Often instead off “a” and “b”, these are called “a” and “c” or “acc” and “cur” for “accumulator” and “current”. But you can call them whatever you want, and if there are more descriptive names, then that works.

1 Like

Another message of help, you truly are a good person, and i mean it !
I wish i knew this website way sooner.
Another way to think through all of this, i am eager to start my projects and use what i learn here :slight_smile:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.