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 ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.