"Condense arrays with reduce" freeCodeCamp challenge

“The accumulator is like a total that reduce keeps track of after each operation. The current value is just the next element in the array you’re iterating through.” I’ve been trying to figure out what this means all day. I don’t really know what to ask except “what does this mean?”

Your browser information:

Your Browser User Agent is: ```Mozilla/5.0 (Windows NT 10.0; Win64; x

Link to the challenge:

The previousVal keeps the running total (here initialized at 0) and the currentVal gets each of the values in the array and we add it to the old previousVal and return it - it becomes the new previousVal for the next iteration. Whenever I’m confused, I use console.log statements to find out what is going one. Like in this code:

const numbers = [12, 3, 15, 13 ]

let sum = numbers.reduce(function(previousVal, currentVal) {
  console.log('previousVal', previousVal, '   currentVal', currentVal)
  return previousVal + currentVal
}, 0)

console.log('final sum', sum)

You can see a pen here.

1 Like