const sum = (…args) => {
return args.reduce((a, b) => a + b, 0);
}
In this lesson I can understand how we are using the arrow function to create a nameless function that accepts (…args)
and how args.reduce
is used to return a single value for the arguments passed in but what I fail to grasp is this portion of the code ((a, b) => a + b, 0)
.
Im feeling dense because even after watching the fcc youtube video on this subject im still not understanding what role a, b, and 0
are doing in that segment of code.
Any help would be appreciated, thank you !
((a, b) => a + b, 0)
these are the two arguments of the reduce method
first there is a function, (a, b) => a + b
and then there is a number, 0
the second optional number of the reduce method is the starting value of the accumulator
I’m not sure I am allowed to link to other websites but after some light reading and your reply I believe i have a better understanding.
So the a
is the accumulator and the b
is the current value and the 0
is, like you said, the starting value of the accumulator , as well as the first element in the array if no initial value is supplied.
Then it simply takes a + b
.
One last question since b
is the current value. when this particular part of code is executed does the code go through iterations where b
will equal the value of each entry in the array at one point or another when it is (being) added to a
or is b
equal to the sum of array already ?
after the first iteration, the accumulator is the returned value of previous iteration
and the current value is the current value of the array being iterated
Alrighty I believe I am understanding it now. Now that I know that the rest parameter does go through iterations of sorts to reach the sum of the entire array it makes it a lot easier to visualize , which for me personally will help me apply it elsewhere and retain the information.