I don’t understand why accumulator + occurrence produces the correct count of an element. My array has four 4s and the function returns that result. So I decided to log the results of accumulator only and occurrence only, I got 0 and 1 respectively. I don’t understand why added together they make four.
The function you supply as the first argument to reduce() is called for every item in the array it is called on. reduce() calls your function with two arguments on each invocation:
accumulator: the value of the second argument to reduce() (here 0) on the first invokation or the result of the former invokation on each subsequent call
current: the value of the current array element.
So on the first invokation your function receives 0 (initial value) and 1 (first array item) as arguments. It then computes occurence to be 1 if the second argument is equal to the value we’re looking for or 0 otherwise. So on the first invocation it’s 0 and your function returns 0 + 0 which is 0.
On the second call your function receives 0 (the result of the last call) and 2 (the value of the second item) and also returns 0.
[…]
On the seventh call the arguments are 0 (the result of the last call) and 4 (the value of the seventh element). Now occurence evaluates to 1 since 4 is equal to the value we search for and the returned value is 1 (0 + 1).
On the eights call the arguments are 1 (the result of the last call) and 4 (the value of the eights element) and the returned value is 2 (1 + 1).
And so on and so forth…