This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
reduce()
is one of these underrated Array methods that can be tremendously useful to accumulate array items. Define an initial value, iterate over all array items and define a callback function to form a combined result.
The beauty: each callback's return value is provided to the next entry callback so that you can sum numbers or regroup the array entries inside of an object.
reduce((previousValue, currentValue) => {
/* ... */
});
reduce((previousValue, currentValue, currentIndex) => {
/* ... */
});
reduce((previousValue, currentValue, currentIndex, array) => {
/* ... */
});
reduce((previousValue, currentValue, currentIndex, array) => {
/* ... */
}, initialValue);
And after all these years, looking at these recude
callback signatures, I discovered that the initial value is optional. 😲
Let's look at an example of summing numbers.
// sum all numbers in the array
// start with `0`
[1, 2, 3, 4, 5].reduce((previousValue, currentValue) => {
console.log(previousValue);
// the return value will be the next `previousValue`
return previousValue + currentValue;
}, 0); // 15
// Output in the console:
// 0
// 1
// 3
// 6
// 10
// 15
You might ask if the first iteration starting with 0
is necessary. And you're correct – it's redundant and is a case for not providing an initial value at all!
// sum all numbers in the array
// start with `1`
[1, 2, 3, 4, 5].reduce((previousValue, currentValue) => {
console.log(previousValue);
// the return value will be the next `previousValue`
return previousValue + currentValue;
}); // 15
// Output in the console:
// 1
// 3
// 6
// 10
// 15
Without a second argument, the reduce
loop starts with the first array entry instead of an initial value – ergo, you'll save one iteration! 🎉
This is a nifty little find! Big thanks to Ramón, who tweeted this tip!
If you want to learn more about the array method, head over to the reduce
entry on MDN.
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis

Stefan Judis | Sciencx (2022-02-18T23:00:00+00:00) Array.prototype.reduce’s initial value is optional (#tilPost). Retrieved from https://www.scien.cx/2022/02/18/array-prototype-reduces-initial-value-is-optional-tilpost/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.