reduce: Folding to One Value in JavaScript
reduce folds an array into a single value with an accumulator: [1,2,3].reduce((t, n) => t + n, 0) sums to 6. The seed (0 here) sets the accumulator's start and type β sums, products, objects, strings, even other arrays all fold from the right seed.
Omitting the seed starts from element zero (and throws on empty arrays) β always pass it explicitly. reduce expresses any aggregation, but readability rules: sums and products yes, labyrinthine multi-jobs better as explicit loops.
Accumulator plus element
(total, n) => total + n runs per element, threading total through β the fold itself.
Seed sets type and start
0 for sums, 1 for products, {} for grouping, [] for flattening β the seed shapes the entire result.
Always pass the seed
Seedless reduce starts at index 1 and throws on [] β explicit seeds remove both hazards.
Keep folds focused
One aggregation per reduce; tangled multi-accumulators belong in readable loops instead.
let nums = [1, 2, 3, 4];let sum = nums.reduce((t, n) => t + n, 0);let grouped = nums.reduce((g, n) => { (g[n % 2 ? "odd" : "even"] ||= []).push(n); return g;}, {});console.log(sum, grouped.even.length);Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself β building beats watching.