JavaScript reduce() function

detailedreduce()Functions in JavaScript

reduce()It is another important method of arrays.

reduce()Execute the callback function on all items of the array and allow the result to be calculated step by step. in caseinitialValuebe appointed,accumulatorIt will be equal to this value in the first iteration.

a.reduce((accumulator, currentValue, currentIndex, array) => {
  //...
}, initialValue)

example:

[1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
  return accumulator * currentValue
}, 1)

// iteration 1: 1 * 1 => return 1 // iteration 2: 1 * 2 => return 2 // iteration 3: 2 * 3 => return 6 // iteration 4: 6 * 4 => return 24 // return value is 24

Download mine for freeJavaScript beginner's manual


More js tutorials: