DEV Community

Tyler Carroll
Tyler Carroll

Posted on

Simple Intro To The reduce() Method In Javascript

I can remember being so excited to learn how to use the reduce method. It seemed so mysterious and advanced at the time. I'm pleased to let you know that even though its powerful and can be hard to understand it's no different than picking up the other functional methods in Javascript, such as filter or map. It just requires practice to become comfortable.

Let's get into it!

A common example you will often see goes like this.

const myArr = [2, 4, 6, 8, 10];

const reducedArr = myArr.reduce((acc, x) => acc + x, 0);

console.log(reducedArr); // 30
Enter fullscreen mode Exit fullscreen mode

How did we arrive at 30 you may ask?

First the callback function passed to reduce is going to take two arguments acc and x, acc is going to stand for accumulator and x for each value in the array. The first arg in the callback acc gets an initial value given to it by the argument after the callback function. Then it will take on the value of the next result.

Imagine it like this acc + x is the equivalent to 0 + 2
then 2 + 4
then 6 + 6
then 12 + 8
then 20 + 10
then acc = 30

We just took and entire array and reduced it to a single value! Pretty dope huh?!

Working with strings

const wordyArr = ['JavaScript ', 'does ', 'not ', 'equal ', 'Java', '!'];

const wordyArrReduced = wordyArr.reduce((acc, x) => acc + x);

console.log(wordyArrReduced);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)