为何JavaScript采用reduce而非fold作为方法名称?
reduce Instead of fold or accumulate Great question—this is a common head-scratcher for folks coming to JavaScript from functional programming backgrounds where fold or accumulate are the standard go-to terms. Let’s unpack this:
Functional programming roots for
fold
In languages like Scheme, Racket, or Haskell,fold(often split intofoldlfor left-to-right processing andfoldrfor right-to-left) is the canonical term for this iterative accumulation pattern. JavaScript’sreducebehaves almost exactly likefoldl—it steps through the array from start to finish, building up a single result value.The pragmatic case for
reduce
The choice ofreducelikely stems from JavaScript’s early design priority: approachability for a broad range of developers, not just functional programming experts. The name directly describes what the method does—it reduces an array of multiple values down to one single output (whether that’s a sum, object, string, etc.). For someone new to FP concepts, "reduce" is immediately intuitive, whereas "fold" requires wrapping your head around the abstract mental model of "folding" a data structure over itself.Perspective from a FP-savvy JS developer
When chatting with that senior JavaScript dev who knows Scheme/Racket, they probably pointed out that whilefoldis more formal in FP circles,reducefits JS’s philosophy of prioritizing clarity for everyday use cases. They might have also noted that JavaScript’sreduceis explicitly tied to arrays, whereasfoldis a generic term that applies to all kinds of data structures (lists, trees, etc.) in functional languages.
To ground this in code, here’s a quick example of how reduce lives up to its name:
// Reducing an array of objects to a single count of completed tasks const completedTaskCount = [ { id: 1, completed: true }, { id: 2, completed: false }, { id: 3, completed: true } ].reduce((acc, task) => task.completed ? acc + 1 : acc, 0); console.log(completedTaskCount); // Output: 2
At the end of the day, it’s a naming choice that balances functional programming functionality with JavaScript’s goal of being accessible to developers of all skill levels and backgrounds.
内容的提问来源于stack exchange,提问作者Jason Park

