A higher order function is a function that either takes a function as an argument or returns a function. This type of function has implementations in many programming languages including Go, JavaScript, Python, etc; and they trend to be a questions used during interviews. Many times I talked to developers about this concept, and they were not familiar with the name, though they have been using it everyday unknowingly, so I decided to cover the topic with a post so it's clear for us all what they are and how they can be useful.
As this topic is widely used among multiple programming languages, I'll be providing code samples in both JavaScript and Python.
Some simple examples
Let's take a look into some simple examples of higher order functions to enter into the topic and work with code, and then we will advance into building some of the popular functions we use which are examples of higher order functions.
Taking a function as an argument
To start let's build a very simple function called doOperation
which takes 3 arguments:
- The function operation
- number1
- number2
Additionally, we will create an operation called sumBothNumbers
which will simply return the sum of 2 numbers.
Python:
def doOperation(operation, number1, number2):
return operation(number1, number2)
def sumBothNumbers(number1, number2):
return number1 + number2
doOperation(sumBothNumbers, 3, 5)
------------
Output
------------
8
JavaScript:
function doOperation(operation, number1, number2) {
return operation(number1, number2)
}
function sumBothNumbers(number1, number2) {
return number1 + number2
}
doOperation(sumBothNumbers, 3, 5)
------------
Output
------------
8
Though in this particular case having the doOperation
function seems redundant if not wrong, there are cases where it can be useful, the doOperation
function can be a part of a library which we can for example extend with our own operations.
Returning a function
Next, we will build a higher order function which will return a function. Our function will be called multiplyBy
and it will take a number as an argument and return a function that will multiply its input by that number.
Python:
def multiplyBy(multiplier):
def result(num):
return num * multiplier
return result
multiplyByThree = multiplyBy(3)
multiplyByThree(4)
------------
Output
------------
12
JavaScript:
function multiplyBy(multiplier) {
return function result(num) {
return num * multiplier
}
}
multiplyByThree = multiplyBy(3)
multiplyByThree(4)
------------
Output
------------
12
Building filter(), map() and reduce()
Let's build a simple version of the popular functions using higher order functions (which they actually are).
filter() aka filtering()
The filtering
function will have 2 parameters, an array
and a test
function and it will return a new array with all the elements that pass the test.
Python:
def filtering(arr, test):
passed = []
for element in arr:
if (test(element)):
passed.append(element)
return passed
def isSuperNumber(num):
return num >= 10
filtering([1, 5, 11, 3, 22], isSuperNumber)
------------
Output
------------
[11, 22]
JavaScript:
function filtering(arr, test) {
const passed = []
for (let element of arr) {
if (test(element)) {
passed.push(element)
}
}
return passed
}
function isSuperNumber(num) {
return num >= 10
}
filtering([1, 5, 11, 3, 22], isSuperNumber)
------------
Output
------------
> (2) [11, 22]
As can be seen, our filter()
function is very easy to code and use to for example get all the super numbers from an array😛.
map() aka mapping()
The function mapping
will take 2 parameters: an array
and a transform
function, and it will return a new transformed array where each item is the result of the transform
function called over each element of the original array.
Python:
def mapping(arr, transform):
mapped = []
for element in arr:
mapped.append(transform(element))
return mapped
def addTwo(num):
return num+2
mapping([1, 2, 3], addTwo)
------------
Output
------------
[3, 4, 5]
JavaScript:
function mapping(arr, transform) {
const mapped = []
for (let element of arr) {
mapped.push(transform(element))
}
return mapped
}
function addTwo(num) {
return num + 2
}
mapping([1, 2, 3], addTwo)
------------
Output
------------
> (3) [3, 4, 5]
reduce() aka reducing()
The function reducing
will take 3 parameters: a reducer
function, an initial value
for the accumulator, and an array
. For each item in the array, the reducer function is called, passing it the accumulator and the current array element. The return value is assigned to the accumulator. When it's finished reducing all the items in the list, the accumulated value is returned.
Python:
def reducing(reducer, initial, arr):
acc = initial
for element in arr:
acc = reducer(acc, element)
return acc
def accum(acc, curr):
return acc + curr
reducing(accum, 0, [1, 2, 3])
------------
Output
------------
6
JavaScript:
function reducing(reducer, initial, arr) {
let acc = initial
for (element of arr) {
acc = reducer(acc, element)
}
return acc
}
function accum(acc, curr) {
return acc + curr
}
reducing(accum, 0, [1, 2, 3])
------------
Output
------------
6
Conclusion
Next time when you get to that interview or simply you see a pattern where a function is either returned or taken as a parameter you will know we are dealing with higher order functions.
Today for the first time I've introduced an article covering more than one language, if you find it a great way to showcase and compare between them, or if you think it was a terrible idea please let me know in the comments or by twitter, I'd love to hear your ideas.
Thanks so much for reading!
If you like the story, please don't forget to subscribe to our free newsletter so we can stay connected: https://livecodestream.dev/subscribe
Top comments (0)