I will start this post out by admitting that JavaScript reduce() was the most intimidating array method for me by far. I wanted to write this how-to guide to help you overcome any fears that you have of using this array method so you can start using it AND understand what you’re writing.

We have all written code we don’t quite understand! And that’s okay. I’m here to help!

JavaScript’s reduce() array method is a powerful and valuable tool. Where it becomes less desirable (for lack of a better term) is the fact that its syntax can be intimidating. It’s not as succinct as say, push()!

No lie, I have to look the syntax up every single time!

What does JavaScript reduce() do?

I’m glad you asked!

Reduce() executes a reducer function against each item in an array, returning a single value. The value returned is the accumulated value. You’ll often see this used with numbers, although it can be used with strings as well to determine counts and frequency.

Intrigued?

reduce()’s syntax is not very cute.

No offense to reduce() whatsoever, but executing this array method is different than the other JavaScript array methods.

BUT, there are major similarities!

The MDN docs, which is where many of us start, make the syntax look a little bit more complicated than the way MOST of us will use JavaScript reduce().

While there are some new things we haven’t seen, there are familiar elements like a callback function. Reduce() accepts a callback function that has two required parameters: accumulator and currentValue.

Optionally, the callback function accepts index and array. We have seen these used previously as well. The final thing the array method accepts, which is also optional, is the initialValue.

Let’s break the syntax down.

For beginners, this is how I would lay out the syntax. The asterisks indicate a required parameter. I’ve omitted the optional parameters index and array to simplify this example.

array.reduce((accumulator*, currentValue*) => {
    //Execute a function
    //You'll often see: accumulator + currentValue
}, initialValue);

//Returns a single value!
  • accumulator: The accumulator does what you might expect-it accumulates the callback function’s return values. You may have seen this expressed as “acc” in someone else’s code, and I want to point out that you can name this value whatever makes sense for you. If you’re not sure what I mean, you’ll see an example shortly.
  • currentValue: The element that is currently being processed in the array. You’ve definitely seen this used in other JavaScript array methods like forEach(). You can also name this whatever makes sense for your code.
  • initialValue: The value to be used as the initial accumulator. This is an optional parameter, so if no initialValue is provided, the first element in the array will be used

#learning-to-code #codingbootcamp #coding #javascript #array-methods

How to Use JavaScript Reduce(): It’s Easier Than You Think
1.35 GEEK