Build a library project

https://www.codecademy.com/paths/web-development/tracks/webdev-intermediate-javascript/modules/learn-javascript-classes/projects/build-a-library

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.

1 Like

Hello, @script0131595176.

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

console.log(b)

Thanks a lot. So it can be omitted as long as the currentIndex is 0? It makes sense now.

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

console.log(b) //22

It wouldn’t matter. Something new always comes up when a question makes its way around the circuit. They’re like comets.

Or is it? Maybe the default value is zero, making that argument (0) moot.

It is. From here:
image

const a = [3,3,3,3]

console.log(a.reduce((a,b) => a * b)) //81 (would be 0 if 0 were the default)

console.log(a.reduce((a,b) => a * b, 0)) //0
1 Like