
上QQ阅读APP看书,第一时间看更新
Using the reduce method
Finally, we have the reduce method. The reduce method receives a function with the following parameters: previousValue, currentValue, index, and array. The index and array are optional parameters, so we do not need to pass them if we do not need to use them. We can use this function to return a value that will be added to an accumulator, which will be returned after the reduce method stops being executed. It can be very useful if we want to sum up all the values in an array. Here's an example:
numbers.reduce((previous, current) => previous + current);
The output will be 120.
These three methods ( map, filter, and reduce) are the basis of functional programming in JavaScript, which we will explore in Chapter 14, Algorithm Designs and Techniques.