I hope i am not replicating this conversation. This might be worth discussing if not clarifying something.
For question 7, I have noticed that many people have this on their code in their forum:
let ratingsSum = this.ratings.reduce((currentSum, rating) = > currentSum + rating);
While looking at the HINT part, Codecademy suggest this:
let ratingsSum = this.ratings.reduce((currentSum, rating) = > currentSum + rating, 0);
My question is with the 0. I know it stands for the currentIndex part of the .reduce() function, but why add the 0 when presumably the iteration will start with the first accumulator and then add the currentValue?
Does the 0 do any specific function to the .reduce()? if not, why mention it? The project walkthrough doesn’t mention or show the 0 in his function. Thanks in advance for the clarification.
The 0 is an optional argument. If provided, it is assigned as the initial value of the accumulator variable. If it is left out, the default value is the first element of the array. Used as you’ve described, currentSum is initially assigned 0, and then the values in the array are added to it. Just for fun, you could try this:
const a = [1,2,3,4,5,6]
const b = a.reduce((x,y) => x * y, 0) //x is the accumulator, y is the current value
It can be omitted unless you have an initial value you want to assign to the accumulator other than the first element of the array. If you wanted to ‘boost’ the ratings you could replace the 0 with 10 for example, so the total sum of the ratings would be 10 plus the sum.
const a = [3, 3, 3, 3] //sum is 12
const b = a.reduce((x,y) => x + y, 10) //x is the accumulator, y is the current value