Member-only story

Learn Javascript reduce() through five simple examples

Chanon Roy
3 min readJul 26, 2021

--

Despite its initially intimidating appearance, the reduce() method is one of the most powerful tools in a Javascript developer’s arsenal.

The reduce method has a clear goal: simplify the very common use case of iterating over an array and processing that data into something meaningful.

In today’s article, we’ll walk through the basic anatomy of the reduce method and show five examples that will help you become intimately familiar with this great tool.

The basic anatomy of the reduce method

This is a very simple skeleton of a reduce method.

arr.reduce((acc, cur, currentIdx, srcArray) => {}, initialValue)

The first argument is a reducer function that has its own important arguments:

  • Accumulator — the ‘remembered’ value that we manipulate and return as the final output of the function.
  • Current Value — the slice of data that we are currently looking at.
  • Current Index — what index of the original array that we are looking at.
  • Source Array — access to the original array that we are iterating through.

Personally, I find the accumulator and current value arguments the most useful.

--

--

Chanon Roy
Chanon Roy

Written by Chanon Roy

🧑🏻‍💻 I write about tech and programming. I'm also fluent in film references

No responses yet