Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

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 reduce callback signatures, I discovered that the initial value is optional. 😲

Here's 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.

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 13 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles