Things I want to accomplish in this Higher Order Function tutorial:
- (In a way that entertains, because HOs can get quite boring.)
- Show fun animations explaining how Higher Order functions work.
Array.map – map all values to an expression.
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.
Here we're simply incrementing all items in the array by 1. But the expression can be anything. The key to map function is understanding that it produces another array with equal number of items except modified in some way.
Array.map(): apply “value + 1” to a set of 7 numbers [1, 2, 3, 4, 5, 6, 7]
- 1] Expression
value + 1is applied to every item in the original array.
.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 accomplish 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.
Array.filter – keep all that match a condition.
Watch out!: there is a small mistake in the animation. It should return
[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 > 5is applied to every item in the original array.
.filter()returns modified copy of array – the original is still available!
- 3] Result:
[6,7,8](only values that passed the condition.)
Array.reduce – reduce all items to a single value.
A common use for a reducer is combining prices of all items in shopping cart.
reduce unique is that it uses an accumulator.
Accumulator is required. Set it to a starting value. Here it is
- 1 Reducer function
Ftakes 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 will combine 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.
More About Higher-Order Functions
On your journey as a web developer you probably already know about variables, arrays, functions, loops and objects...it's a good time for your next challenge.
I remember that at one point in my life every time 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.
Why you should learn Higher Order Functions sooner than later?
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.)
What are higher order functions and what do they help with in general?
- 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.
- 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.
- 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.
- 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.
- 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.
- 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 Smart
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.)
Use higher-order functions for their intended purpose only
It's possible to make map function do filter's work because essentially they are both for-loops (in native implementation under the hood.) But that'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.
#Octopack is my coding book bundle.
Hey readers! At the end of each tutorial I advertise my coding book bundle. I don't know if it's going to work as I don't really do marketing well. But I decided to follow this protocol just to see what happens.
I don't know who is reading my tutorials but I put together this coding book bundle that contains some of the best books I've written over the years. Check it out 🙂 I reduced price to some regions like India, Nigeria, Cairo and few others. Prices are just so different here in the U.S. and all over the world.
You can get Octopack by following my My Coding Books link.