Skip to content

Instantly share code, notes, and snippets.

@itsgreggreg
Last active August 29, 2015 14:24
Show Gist options
  • Save itsgreggreg/a3dbdddf386cd5244f39 to your computer and use it in GitHub Desktop.
Save itsgreggreg/a3dbdddf386cd5244f39 to your computer and use it in GitHub Desktop.
What is reduce

###Reduce is just a convenience method.
You can write any reduction as a simple loop

Given this list:

var list = [1,2,3,4,5];

This "reduction"

var result = _.reduce(list, function(item, memo){
  return memo+item;
});

Does the exact same thing as this while loop

i = 0;
result = 0;
while(i < list.length){
  result = result + list[i];
}

Another example

Given this function and list:

function biggerNumber(a,b){
  if(a > b){
    return a;
  } else {
    return b;
  }
}

var list = [23,2342,3,39498,33230142,982];

This Reduction

var biggestNumber = _.reduce(list, biggerNumber);

Does the same thing as this for loop:

var biggestNumber = 0;
for(var i = 0, len = list.length; i < len; i = i +1){
  biggestNumber = biggerNumber(list[i], biggestNumber);
}

###So why have reduce?

  • Less to mess up
  • No iterator to manage
  • No memo to manage
  • Function body contains only code related to your reduction
  • reduce() is an expression
  • Ultimately, programmer convenience

The big takeaway: In programming there are many ways to do the same thing. Reduce is important because it teaches you about higher order functions and using managed iteration instead of doing the iteration manually in a while or for loop. But ultimately every reduction can be written as a simple loop, we just use reduce because it makes thinking about our code easier. :)

###Side Note What are higher order functions (HOFs), why do people keep talking about them, why are they important?

A higher order function is simply:
A function that can take a function as a parameter or return a function.
That's it.

####What really? Yes. If you are learning javascript as your first programming language, none of this matters. Javascript has HOFs built in and so you've never had to program without them no do you think they're new and awesome and strange. 15/20 years ago not a lot of people programmed with HOFs and so they were kind of a big deal. Now-a-days I don't know why we even bother giving the concept so much attention. It's probably just because programmers like talking about programming.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment