Loading course content...
Loading course content...
Code Playground is only enabled on larger screen sizes.
The example in the previous lesson is one of the most common applications of higher-order functions.
function diameter(radius) {
return 2 * radius;
}
function circumference(radius) {
return 2 * Math.PI * radius;
}
function calculate(arr, logic) {
let output = [];
for (let r of arr) {
output.push(logic(r));
}
return output;
}
circles = [2, 10, 13, 7, 8, 6, 5];
console.log(calculate(circles, diameter));
console.log(calculate(circles, circumference));The function calculate() is acting as a container for smaller functions, such as diameter() and area(). By passing different logic to calculate(), you can use it to calculate different things.
Of course, there are some other applications of higher-order functions that are a bit more difficult to understand, but if you use these techniques well, they'll significantly improve the quality of your code.
For instance, the calculate() example accepts a function as the input, but recall the definition of a higher-order function:
Higher-order function (HOF) is a type of functions that operate on other functions by either accepting them as input arguments, or returning them as the output.
Interesting things happen when you make a function return another function as the output.
The first example we are going to demonstrate is called a function factory. It is a function that returns new functions based on the input.
function multiplier(mul) {
return function calc(number) {
number * mul;
};
}In practice, it is generally recommended to use the arrow function syntax here. It will make you code shorter and easier to read.
function multiplier(mul) {
return (number) => number * mul;
}The function multiplier() accepts an input argument mul, and when it is executed, it will return the function:
(number) => number * mul;This new function then accepts an input argument number, and returns number * mul.
We can use this technique to create different functions with different purposes, hence the name, function factory.
For example:
function multiplier(mul) {
return (number) => number * mul;
}
let double = multiplier(2); // Passing 2 to multiplier() to create double()
let result = double(5);
console.log(result);In this case, let double = multiplier(2) creates the function:
let double = function (number) {
return number * 2;
};Similarly, you can reuse the same function factory to make other functions by passing different mul to multiplier():
let double = multiplier(2);
let triple = multiplier(3);
let quadruple = multiplier(4);console.log("Hello, World!");