Higher order functions
As we discussed in previous post, functions are first-class citizens, which means they can be assigned to variables, passed as arguments to other functions, and returned as values from other functions. This is the foundation of higher order functions.
What Are Higher Order Functions?
A higher order function is a function that takes one or more functions as arguments or returns a function as its result. In simpler terms, it’s a function that operates on other functions, either by taking them as inputs or by producing them as outputs. Here is an example of our own higher order function:
function write() {
console.log("I am a callback function");
}
function higherOrderFunction(func) {
console.log("I am higher order function");
func();
}
higherOrderFunction(write);
Why Are Higher Order Functions Useful?
Higher order functions enable you to write more reusable and modular code. They promote the concept of separation of concerns and allow you to abstract away common patterns into reusable functions. This makes your code more readable and easier to maintain.
Examples of Higher Order Functions
Let’s dive into some built-in common higher order functions in JavaScript and see how they work:
Map
The map
function is used to transform each element in an array and return a new array with the transformed values.
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(function (num) {
return num * num;
});
console.log(squaredNumbers); // [1, 4, 9, 16, 25]
As we will later see in ES6 post, this can be written even more concisely.
Filter
The filter
function is used to create a new array containing elements that pass a specific condition.
const scores = [85, 92, 78, 95, 88];
const passingScores = scores.filter(function (score) {
return score >= 90;
});
console.log(passingScores); // [92,95]
Reduce
The reduce
function is used to accumulate values in an array into a single result.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(function (accumulator, currentValue) {
console.log(accumulator, currentValue);
return accumulator + currentValue;
}, 0);
console.log(sum); // 15
Reduce is a bit more complex so let’s go through it. accumulator
is accumulation of all the values that were returned so far and currentValue
is the current value being processed. There is also second parameter that in our case is 0
. This is initial value of accumulator
at the beginning of first iteration. So in first iteration we would have accumulator = 0
and currentValue = 1
then in second accumulator = 0+1 = 1
and currentValue = 2
and so on.
What now?
Try to make each of these functionalities without using higher order functions but what you learned up until now (hint: loops, functions…)