Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialrymatech
4,671 PointsCan someone explain how this sum code works?
var sum = [1, 2, 3].reduce((a, b) => a + b, 0);
console.log(sum); // 6
I know the above code calculates the sum of an array but how?
"a" and "b" are the parameters, then "a" and "b" are added together but what is the 0 for?
1 Answer
Moosa Bonomali
6,297 PointsThe reduce function is executed as follows;
arr.reduce(callback[, initialValue])
The initialValue is optional. In your case 0 is the initial value. In this case it may not be necessary to include the 0, if you had a different initial value, then this value would have been added to sum of your array.
The callback function takes 4 parameters, 2 of which are required. In your case a and b.
(a , b)
a is the accumulator - it keeps track of the total so far b is the current value been processed. The return value of the callback function
=> a + b
will be stored in a until all array elements are processed.