Is this really a dev blog if I don't post about .reduce()?!

When I moved into ES6 iterator methods, I was excited. Sure vanilla JS was fun and all, but I was seriously ready to understand faster more concise ways to do things - and then came .reduce()!

😱 Reduce Scares People — Just Look at It

let numArray = [1, 2, 3, 4, 5];
numArray.reduce((acc, cur) => acc + cur, 0);

Is this some strange incantation? Am I turning lead into gold? Well, sort of! Reduce is like JavaScript alchemy, and I love it.

🧺 What .reduce() is Doing

  • With every iteration (loop over the array), you can pick something up and put it in your magic basket.
  • The accumulator (often shortened to acc) is your basket — and you get to decide what kind of basket you want to carry!
  • The initial value you give to .reduce() is the starting basket:
    • 🧮 A number (sum up values)
    • ✏️ A string (concatenating stuff)
    • 🗂️ An object (building new structures)
    • 📦 An array (flattening, regrouping, etc.)
  • Every time you return from the function, you hand the basket back to .reduce() for the next loop.

  • When .reduce() finishes walking through the array, it hands you back the final, filled basket.

🔢 A Basic Example: Summing Numbers

We'll use .reduce() to return the total of all the numbers in an array:

const arrayOfNums = [1, 2, 3, 4, 5];
const sumOfNumbers = (array) => {
  return array.reduce((acc, cur, i) => {
    console.log(`iteration ${i + 1}`)
    console.log(`accumulator: ${acc}, currentValue: ${cur}`)
    console.log(`${acc} + ${cur}`)
    acc += cur;
    console.log(`total: ${acc}\n`);
    return acc;
  }, 0);
}
// sumOfNumbers(arrayOfNums) returns 15

👀 Logging What Happens

Those console.log() statements are everything when it comes to really seeing what's happening when the method runs.

iteration 1
accumulator: 0, currentValue: 1
0 + 1
total: 1

iteration 2
accumulator: 1, currentValue: 2
1 + 2
total: 3

iteration 3
accumulator: 3, currentValue: 3
3 + 3
total: 6

iteration 4
accumulator: 6, currentValue: 4
6 + 4
total: 10

iteration 5
accumulator: 10, currentValue: 5
10 + 5
total: 15

🧠 Breaking Down the Callback: acc, cur, and More

When you use .reduce(), you're passing in a callback function that runs once for every item in the array.
That callback can take up to four parameters. Let's demystify them:

  • acc (the accumulator) – Think of this as your basket. It starts with whatever initialValue you pass into reduce. Here, we set it to 0, so the accumulator begins at 0 before adding the first number.

  • cur (the current value) – This is the current item from the array that you're looking at during the iteration.

  • index (optional) – The position of the current item in the array - sometimes just shortened to i. Super useful when you want to know where you are.
    (And don’t forget: arrays are zero-indexed — meaning the first element has an index of 0, the second has 1, and so on.)

  • array (optional) – The original array being reduced.
    (Apparently handy, but to be honest... I've never really needed it.)

You don’t have to include all four — just the ones you actually need.

📝 A Slightly Spicier Example: Building a Sentence

Take an array of words. We'll use .reduce() to build a sentence and utilize index for more than logging.

const arrayOfWords = ["My", "name", "is", "Beza"];
const buildSentence = (arr) => {
   return arr.reduce((acc, cur, i) => {
     if (i === arr.length - 1) {
       acc += cur + ".";
     } else {
       acc += cur + " ";    
     }
     return acc;
   }, "")
}
// buildASentence(arrayOfWords) returns "My name is Beza."

🔍 What's Different This Time?

Notice how we added some conditions:

  • If we're at the last word (i === arr.length - 1), we add a period

  • Else we add a space after the word

🛠 Not Just Gathering — Deciding

.reduce() isn’t just gathering stuff — it’s also deciding how to gather based on where we are in the array!
It can build, shape, and transform as it walks through the data — and you, the developer, are the magician casting the spell.
Once it clicks, the possibilities for its use feel endless.

🪄 Start Small and Keep Practicing

If .reduce() still feels confusing, don't worry - it's completely normal at first.
Don't give up. Circle back to the basic numbers example and add your own console.log() statements.

The more you watch the basket being filled piece by piece, the more natural .reduce() will start to feel. And when it clicks, you'll feel the magic!