Search code examples
javascriptreduceternary

Reduce and ternary operator .The ternary operator in reduce method has zero in the 'else' part and return the wrong answer


My reduce function returns 27 instead of 77. I would like to know why this is happening. I AM NOT LOOKING FOR THE SOLUTION. I know the solution, but I don't know why 0 or null in the else portion of my ternary operator doesn't give the correct answer.

const sumFive = arr => arr.reduce((sum, value) => value > 5 ? sum + value : 0, 0)

sumFive([1, 5, 20, 30, 4, 9, 18])

Solution

  • You're resetting the accumulator to 0 every time the iteration comes across a value of 5 or less.

    iteration so far --- accumulator returned by iteration
    
    1 --- 0
    1, 5 --- 0
    1, 5, 20 --- 20
    1, 5, 20, 30 --- 50
    1, 5, 20, 30, 4 --- 0
    1, 5, 20, 30, 4, 9 --- 9
    1, 5, 20, 30, 4, 9, 18 --- 27
    

    You need to return the current accumulator value instead of 0 if you want your function to produce the desired output.