Javascript fold reduce functional programming
What is the role of reduce (or fold) in JavaScript functional programming?
This question explores how the reduce() method works in JavaScript, allowing you to transform arrays into a single value and enabling powerful functional programming techniques like data aggregation and transformation.
In functional programming with JavaScript, reduce() (also known as fold in other languages) is a powerful and flexible method used to process and combine all elements of an array into a single value. It's one of those tools that might seem confusing at first but becomes incredibly useful once you get it.
So, what exactly does reduce() do?
It takes a callback function and an initial value, then applies the callback to each element in the array — building up a result along the way.
Basic Example: Sum of an array
const numbers = [1, 2, 3, 4];
const total = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(total); // Output: 10
Here:
- acc is the accumulator (the running total).
- curr is the current value from the array.
- 0 is the initial value of the accumulator.
Why is it called “fold”?
In functional programming, a fold is a way to "collapse" a list into a single value — which is exactly what reduce() does.
What can you use reduce() for?
- Summing or multiplying values
- Flattening nested arrays
- Building objects from arrays
- Removing duplicates
- Counting occurrences
Key benefits:
- Encourages writing clean, declarative code
- Replaces many loops with one elegant function
- Works well with other functional methods like map() and filter()