Blog Post: Better Reduce Example
Many programming languages include a reduce()
function (or a variant such as Accumulate()
, array_reduce()
, or Stream.reduce()
).
In most cases, documentation demonstrates how to use this function by replicating a simple sum operation:
// (this is pseudocode)
[1,2,3,4,5].reduce(
function (a, b) {
return a + b;
}
)
The Problem
While this code is syntactically correct, the example lacks clarity because the arguments aren't given meaningful names. A new learner must consult additional documentation—or guess—to understand which argument is the accumulator and which is the current element. That momentary pause breaks flow and makes debugging real-world reduce()
functions slightly harder—especially since reduce()
is already relatively uncommon. (In Python, for example, it was publicly demoted 🔗 from a built-in function to a library function in the transition from version 2 to 3.)
Two Solutions
There are two small improvements that could make this documentation more helpful.
Descriptive Argument Names
The first improvement is to use more descriptive argument names in the lambda or function—like in the example below:
[1,2,3,4,5].reduce(
// accumulator
// element
function (acc, ele) {
return acc + ele;
}
)
[1,2,3,4,5].reduce(
// current total
// (next) value
function (curr, val) {
return acc + ele;
}
)
Even abbreviated names can give developers a clearer idea of each argument’s purpose.
A Different Example
The second improvement is to consider replacing the sum()
example with something slightly more illustrative, such as computing the maximum value of an array:
[1,2,3,4,5].reduce(
// current largest value
// (next) element
function (curr, ele) {
return acc + ele;
}
)
Here, the comparison logic helps the reader naturally infer the role of each argument.
Key Takeaway
This is a reminder that documentation—especially code examples—should be reviewed for ambiguity. Even small naming decisions can significantly influence how code is understood and reused.