A so called accumulator, in our case it's the sum. The value that you return in the reducer function becomes the accumulator for the next iteration.
The value of the current iteration, our boolean!
We want to count total amount of times we encounter true.
In other words: the sum of all booleans with value true.
In other other words, if the value of our current iteration is true, we want to increment the sum by 1.
In pseudo code: sum = sum + (true ? 1 : 0).
So what about sum + boolean???
We need to use a smart little trick: if you convert a boolean to a number, then true will become 1 and false becomes 0. So Number(true) === 1.
If we use the addition operator+, JavaScript will automatically convert values to numbers for you!
Now, you may have noticed that we never declare sum anywhere. We never tell the reduce function to start counting at 0. Next to the reducer function, Array.reduce() can take a second parameter, which is the initial value for the accumulator. If we do not pass an initial value, it will just take the first value of our array.
There you have it!
We can just add the boolean to our sum, and it will add 1 if it is true or 0 for false, exactly what we want.
Instead of counting sheep, how about we reduce them?
What's going on here? Where did the sum come from?? Adding the a boolean to a sum??? Are you nuts?!
Ok let's go step by step.
sum
. The value that you return in the reducer function becomes the accumulator for the next iteration.true
.true
.true
, we want to increment thesum
by 1.sum = sum + (true ? 1 : 0)
.sum + boolean
???true
will become1
andfalse
becomes0
. SoNumber(true) === 1
.+
, JavaScript will automatically convert values to numbers for you!Now, you may have noticed that we never declare
sum
anywhere. We never tell the reduce function to start counting at 0. Next to the reducer function,Array.reduce()
can take a second parameter, which is the initial value for the accumulator. If we do not pass an initial value, it will just take the first value of our array.There you have it!
We can just add the boolean to our sum, and it will add 1 if it is
true
or 0 forfalse
, exactly what we want.That's so cool Edwin! Reduce sounds like a very interesting prototype that I'm going to look into more!