Mastering JavaScript’s reduce(): From Basics to Advanced Use Cases
This article explains the ES5 Array.prototype.reduce() method, compares it with forEach and map, details its syntax and parameters, provides step‑by‑step code examples—including handling of initial values and object arrays—and notes browser compatibility and library alternatives.
What is reduce()?
The Array.prototype.reduce() method takes a callback function and optionally an initial value, iterating over an array from left to right and accumulating a single result. It was added in ES5 and differs from forEach and map by returning a value.
Syntax
arr.reduce(callback[, initialValue])
Callback parameters
previousValue – the value returned by the previous callback invocation, or the initial value if supplied.
currentValue – the current array element being processed.
currentIndex – the index of the current element.
array – the array on which reduce() was called.
initialValue (optional) – the value passed as previousValue on the first call.
Simple examples
Calculate the sum of [1,2,3,4] using three different approaches.
forEach implementation
var arr = [1,2,3,4], sum = 0;
arr.forEach(function(e){ sum += e; }); // sum = 10map implementation
var arr = [1,2,3,4], sum = 0;
arr.map(function(obj){ sum += obj; }); // sum = 10reduce implementation
var arr = [1,2,3,4];
var total = arr.reduce(function(pre, cur){ return pre + cur; }); // total = 10Parameter breakdown
1. Without initialValue
var arr = [1,2,3];
arr.reduce(function(pre, cur, index, arr){ debugger; return pre + cur; });During debugging you can observe the values of pre, cur, index and arr at each step.
2. With initialValue
var arr = [1,2,3];
arr.reduce(function(pre, cur, index, arr){ debugger; return pre + cur; }, 10);Providing an initialValue adds an extra recursion step; the accumulator starts with the supplied value.
More practical use cases
Product of an array
var arr = [1,2,3];
var product = arr.reduce(function(pre, cur){ return pre * cur; }); // product = 6Maximum value
var max = arr.reduce(function(pre, cur){ return pre > cur ? pre : cur; });Transforming an array of objects into a formatted string
var arr = [{name:'brick1'},{name:'brick2'},{name:'brick3'}];
function carryBricks(arr){
return arr.reduce(function(prev, current, index, array){
if(index === 0){
return current.name;
} else if(index === array.length - 1){
return prev + ' & ' + current.name;
} else {
return prev + ', ' + current.name;
}
}, '');
}
// Result: "brick1, brick2 & brick3"Appending to an existing string
var bricks = 'brick1, brick2, brick3, ';
function carryBricks(arr, bricks){
return arr.reduce(function(prev, current, index, array){
if(index === 0){
return prev + current.name;
} else if(index === array.length - 1){
return prev + ' & ' + current.name;
} else {
return prev + ', ' + current.name;
}
}, bricks);
}
// Result: "brick1, brick2, brick3, brick1, brick2 & brick3"Compatibility notes
In Node.js the method works out of the box. In older browsers (IE8 and below) reduce is not supported; a polyfill or a jQuery plugin can be used. The jQuery reduce plugin has been discussed for many years and remains available.
Summary
forEach executes a function for each element without returning a new array.
map creates a new array by applying a function to each element.
reduce aggregates array elements into a single value, optionally starting from an initialValue.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Aotu Lab
Aotu Lab, founded in October 2015, is a front-end engineering team serving multi-platform products. The articles in this public account are intended to share and discuss technology, reflecting only the personal views of Aotu Lab members and not the official stance of JD.com Technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
