DEV Community

Understanding reduce in JavaScript

SavagePixie on September 05, 2019

When I first started learning JavaScript, I had some trouble grasping reduce(). I have heard of other people having trouble with it when they start...
Collapse
 
angelfire profile image
Andrés Bedoya

That's why it's important use well named variables, imagine that your first approach with reduce was this way:
arr.reduce((accumulator, currentValue) => accumulator + currentValue);

Much better, don't you think so? It's almost self explanatory...

Collapse
 
savagepixie profile image
SavagePixie

I'm pretty sure I would still have found a way to be confused by it, hahaha

But I do agree that clear naming goes a long way to help understand code.

Collapse
 
chrisidakwo profile image
Chris Idakwo

This is still confusing to someone who has never worked with reduce(). But then makes explaining it a bit more easy.

Collapse
 
htissink profile image
Henrick Tissink

This is a great post - really well written and clear; it removes all the confusion surrounding reduce. Thanks Pixie! :]

Collapse
 
mshirlaw profile image
Matt Shirlaw

Nice explanation, well done 👏

Collapse
 
pinz88 profile image
Matthew Pinzino

This was awesome, thanks for the article.

Collapse
 
toddcoulson profile image
Todd Coulson

"I understand that a and b are supposed to be elements in the array, but how on earth does JavaScript know which one is which?"

I don't understand any of these questions you were asking when first analyzing reduce. First a and b were not elements in an array, but rather parameters, that is how they are figured out which are which. The person asking those questions, don't understand the difference between functions and arrays.

Collapse
 
savagepixie profile image
SavagePixie

Well, b is an element of the array in the sense that it represents the element currently being processed in the array. Even MDN speaks of it that way (and even a would be an element in the array for the first invocation of the callback function in that particular case.)

At any rate, I think the root of our misunderstanding is that you seem to be taking my words as talking about their syntactic function (so to speak), while I'm talking about the value they represent and how reduce() deals with them.

Collapse
 
hongphuc5497 profile image
Hong Phuc

Thanks, sometimes I forget how to use the function and topic like this is so helpful

Collapse
 
andrewyhchan994 profile image
Andrew Chan

Hi, where would the semicolons be placed in example 2?

Collapse
 
iglesfe profile image
Federico Iglesia • Edited

holy s**t!!! it's so clear now, thank you!!