Higher-order functions .map, .filter and .reduce in JavaScript

Things I want to accomplish in this Higher Order Function tutorial:

  1. Introduce newbies to the idea of Higher Order Function in JavaScript.
  2. (In a way that entertains, because HOs can get quite boring.)
  3. Show fun animations explaining how Higher Order functions work.

JavaScript Grammar book explains higher-order functions in detail and also shows you how they work by creating your own version of .map() method. (Among many other great examples.)

To kick off this tutorial I’ll start with animated example of higher-order function map. It modifies each item in the original array and returns a copy. In this case we’re simply incrementing all array items by 1. Or in other words it “maps” a new value to existing items by following the supplied expression.

Image for post
Image for post

**Array.map(): apply “value + 1” to a set of 7 numbers [1, 2, 3, 4, 5, 6, 7]**

1] Expression ```value + 1``` is applied to every item in the original array.
2] .map()``` returns a modified copy of the array leaving original untouched.
3] Result: ```[2,3,4,5,6,7,8]``` (a copy of the original array is created.)

The higher order function map can be used for mapping items in one format to another. (Number to String, for example.)

Like any other higher-order function map can be applied to many different problems. It depends on what you’re trying to do with a given dataset.

Higher-order functions are abstract on purpose. They are not here to tell you exactly what problems you should be solving using them. They simply capture a commonplace pattern present in many basic logical problems.

Image for post
Image for post

Watch out! there is a small mistake in the animation. It should return [6,7], not [6,7,8]. I’ll fix it shortly. . .but you can’t learn anything without admitting mistakes. A mistake is simply an inverse of understanding how something actually works:)

  1. function value > 5 is applied to every item in the original array.
  2. .filter() returns modified *copy* of array: the original is still available!
  3. Result: [6,7,8] (only values that passed the condition.)

A common use for a reducer is combining prices of all items in shopping cart.

What makes reduce unique is that it uses an accumulator.

Accumulator is required. Set it to a starting value. Here it is 0.

Image for post
Image for post

1] Reducer function F takes value and accumulator.
2] In this example .reduce(v, a) returns the sum of all values.
3] Result: 28 (the sum of all numbers in the original array.)

Higher-order functions map, filter and reduce have been around for a long time. They are often seen as part of Functional Programming style. They work on a set of data (e.g. Array) by transforming it from its original state to some modification.

For example the filter function will physically remove items from an array based on a logical criteria passed to the function in the form of an equation.

The map function will map one value to another. One basic (and perhaps practically useless) example is incrementing all numbers in a set by 1.

And reduce combines all items into one value. For example this is often done to calculate the total of all items in a shopping cart. But use cases are endless.

Animations in this tutorial only tried to make attempt at visualizing purpose of each higher order function. This is done merely for entertainment as you probably won’t learn them in depth from simply looking at the visuals.

On your journey as a webdev you probably already know about variables, arrays, functions, loops and objects…it’s a good time for your next challenge.

I remember that time in my life when I had to solve a problem involving a large set of items I would simply write a for-loop.

> I used to write for-loops for everything. They made me feel comfortable because it gave me control over the logic of my code. I knew exactly what would happen to data on each iteration.

Here’s a simple for loop I’d write to increment all array items by 1:

let numbers = [1,2,3];
let copy = [];
for (let x = 0; x < numbers.length; x++)
copy[x] = numbers[x] + 1;
console.log(copy); // [2,3,4]

I felt dumb when I saw a coder on our team use git to commit a chunk of code containing a higher-order function to sort out a list of React components.

Although HO functions produce same results as a well-crafted for loop it felt like a black box you throw a condition at and it simply applies intended actions.

At first sight higher-order functions were easy to read. But at the same time hard to understand. Here is a very basic example of **.map** function:

/* Example of a higher-order functions .map */
let copy = [1, 2, 3].map(value => value + 1);
console.log(copy); // [2,3,4]

Same effect as for-loop above. But much cleaner code.

In this example the function .map will create a copy of the original array [1,2,3] with all of its items incremented by 1 which will produce a new array [2,3,4].

This classic example often used as an introduction to HO functions.

Higher-order functions exist natively on objects of type Array. So you can already start using them but not all Array methods are higher-order functions.

Looking at their simple syntax I could actually understand what they were doing. But I had no idea how to write my own, how to modify them or what they were.

On your way to JavaScript mastery (*or any computer language*) you might want to deepen your knowledge of higher-order functions and their use cases.

If you become employed to work on a commercial project you are not going to get away writing clean code with just the standard while and for-loops (*by the way, there is nothing wrong with them.*)

  1. Technically speaking… A *higher-order function* is defined as a function that takes another function as one of its arguments. In this context normal functions you’ve been using all along are referred to as **first order functions.
  2. Clean code. If you are interested in clean code higher order functions are definitely your friend. They consist of pre-written do, while or for-loops and this code already exists natively as part of JavaScript language specification.
  3. Pre-written, Multi-purpose for-loops. Wait. Don’t write that for loop. There is already an existing higher-order function that can help you solve the same logical problem you’re coding in a for-loop.
  4. Data modification: Higher-order functions help modify large datasets by following a condition. Different HO functions exist for a reason. Each one can help you remove items, convert them to different format or map them.
  5. Doing bulk actions: Let’s say you have 1000 items in your array. You want to perform an operation on each item. Instead of doing it by hand to each item (which would be redundant) simply pass a rule to a higher-order function and it will perform that action on the entire set of items.
  6. Abstracting common logic: Let’s say you have a list of animals and insects in an array. Without higher-order functions to “remove all insects” you would write your own custom loop. Or simply pass a condition “not an insect” to a higher order functions such as filter and it will do all the work for you. Filtering datasets is an incredibly common action in computing.
  7. Used in React: React is a popular JavaScript library. It uses components to render HTML elements. Higher order functions like filter can help you with sorting lists of items. Using filter in combination with React’s render function you can render a filtered set of items from a set. For example, to only display Admin accounts from a set of all registered users.
  8. Functional Programming: Although there is much more to *functional programming* than simply using higher-order functions, they definitely play an important role in it.

Higher-Order Functions are friends. Use them over for-loops.

No higher-order function is made alike. They are similar but not the same.

Each function should be used in proper context.

The output is controlled not only by the function but also by logical criteria (passed to the function in a form of what looks a lot like a mathematical equation often in the format of arrow function.)

It’s possible to make map function do filter’s work because essentially they are both for-loops. But it’s not recommended. Try to apply the proper function to the logical situation at hand.

Best thing you can do is simply learn the actual purpose of each method. Often that simply takes getting your hands dirty and practice writing code.

Whenever you see a problem involving hundreds or thousands of entries or items, think of whether a suitable higher-order array method already exists to solve that problem instead of writing your own code. More than often it does.

Hope this tutorial helped someone out there.

You can’t go wrong with these coding reference books available via Amazon.

Written by

Issues. Every webdev has them. Published author of CSS Visual Dictionary https://amzn.to/2JMWQP3 few others…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store